gpt4 book ai didi

java - 如何使用匹配的 DER 私钥解密 PEM 公钥加密字节数组?

转载 作者:行者123 更新时间:2023-11-30 17:05:11 24 4
gpt4 key购买 nike

所以我正在创建一个基本的套接字程序,我想将 C 中的加密字符串发送到 Java 程序。我的 C 程序使用公共(public) PEM key 加密该字符串。我已将匹配的私有(private) PEM key 转换为 DER key ,现在想要解密发送到我的 Java 程序的字符串。我该怎么做?

目前,我在尝试按原样运行代码时收到 IllegalBlockSizeException,指出“数据不得长于 256 字节”。

这就是我现在所拥有的:

C 客户端程序...

 //Get our public key from the publickey file created by server
FILE *publicKeyFile = fopen("publicKey.pem", "rb");
RSA *rsa = RSA_new();
rsa = PEM_read_RSA_PUBKEY(publicKeyFile, &rsa, NULL, NULL);
if(rsa == NULL) {
printf("Error with public key...\n");
}
else {
//if the public key is correct we will encrypt the message
RSA_public_encrypt(2048, sigMessage, sigMessage, rsa, RSA_PKCS1_PADDING);
}

Java解密...

    public static String decrypt(byte[] encryptedMessage) {

try {
Cipher rsa;
rsa = Cipher.getInstance("RSA");
PrivateKey ourKey = getKey("resources/privateKey.der");
rsa.init(Cipher.DECRYPT_MODE, ourKey);
byte[] utf8 = rsa.doFinal(encryptedMessage);
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public static PrivateKey getKey(String filePath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {

File f = new File(filePath);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();

PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}

最佳答案

除非您拥有超过 16K 的 RSA key ,否则您无法使用 RSA 加密 2,048字节。您可能有一个 2048 位 RSA key ,这将您限制在 256 字节以下。查看 openssl 手册页 RSA_public_encrypt :

flen must be less than RSA_size(rsa) - 11 for the PKCS #1 v1.5 based padding modes, less than RSA_size(rsa) - 41 for RSA_PKCS1_OAEP_PADDING and exactly RSA_size(rsa) for RSA_NO_PADDING. The random number generator must be seeded prior to calling RSA_public_encrypt().

RSA_size :

RSA_size() returns the RSA modulus size in bytes. It can be used to determine how much memory must be allocated for an RSA encrypted value.

不过,您不应该使用 2048 位 key 加密完整的 256 字节。您希望始终使用带有 RSA 加密的随机填充,并选择 OAEP 而不是 v1.5。

关于java - 如何使用匹配的 DER 私钥解密 PEM 公钥加密字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35420538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com