帮我写一段使用RSA加密解密的Kotlin和C++的代码
时间: 2024-04-29 21:21:07 浏览: 205
Kotlin代码:
```kotlin
import java.security.KeyPairGenerator
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.util.Base64
import javax.crypto.Cipher
fun main() {
val message = "Hello, World!"
// Generate RSA key pair
val keyPairGenerator = KeyPairGenerator.getInstance("RSA")
keyPairGenerator.initialize(2048)
val keyPair = keyPairGenerator.generateKeyPair()
val publicKey = keyPair.public as RSAPublicKey
val privateKey = keyPair.private as RSAPrivateKey
// Encrypt message using public key
val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
cipher.init(Cipher.ENCRYPT_MODE, publicKey)
val encryptedMessage = cipher.doFinal(message.toByteArray())
val encryptedMessageBase64 = Base64.getEncoder().encodeToString(encryptedMessage)
// Decrypt message using private key
cipher.init(Cipher.DECRYPT_MODE, privateKey)
val decryptedMessage = cipher.doFinal(Base64.getDecoder().decode(encryptedMessageBase64))
val decryptedMessageString = String(decryptedMessage)
println("Original message: $message")
println("Encrypted message: $encryptedMessageBase64")
println("Decrypted message: $decryptedMessageString")
}
```
C代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
int main() {
const char* message = "Hello, World!";
const int keySize = 2048;
// Generate RSA key pair
RSA* rsaKeyPair = RSA_generate_key(keySize, RSA_F4, NULL, NULL);
RSA* rsaPublicKey = RSAPublicKey_dup(rsaKeyPair);
RSA* rsaPrivateKey = RSAPrivateKey_dup(rsaKeyPair);
// Encrypt message using public key
int encryptedMessageLength = RSA_size(rsaPublicKey);
unsigned char* encryptedMessage = (unsigned char*)malloc(encryptedMessageLength);
RSA_public_encrypt(strlen(message), (unsigned char*)message, encryptedMessage, rsaPublicKey, RSA_PKCS1_PADDING);
char* encryptedMessageBase64 = (char*)malloc(encryptedMessageLength * 2);
int encryptedMessageBase64Length = EVP_EncodeBlock((unsigned char*)encryptedMessageBase64, encryptedMessage, encryptedMessageLength);
// Decrypt message using private key
int decryptedMessageLength = RSA_size(rsaPrivateKey);
unsigned char* decryptedMessage = (unsigned char*)malloc(decryptedMessageLength);
RSA_private_decrypt(encryptedMessageLength, encryptedMessage, decryptedMessage, rsaPrivateKey, RSA_PKCS1_PADDING);
char* decryptedMessageString = (char*)malloc(decryptedMessageLength + 1);
memcpy(decryptedMessageString, decryptedMessage, decryptedMessageLength);
decryptedMessageString[decryptedMessageLength] = '\0';
printf("Original message: %s\n", message);
printf("Encrypted message: %s\n", encryptedMessageBase64);
printf("Decrypted message: %s\n", decryptedMessageString);
RSA_free(rsaKeyPair);
RSA_free(rsaPublicKey);
RSA_free(rsaPrivateKey);
free(encryptedMessage);
free(encryptedMessageBase64);
free(decryptedMessage);
free(decryptedMessageString);
return 0;
}
```
阅读全文