gpt4 book ai didi

java - Java中RSA公钥生成和加密的有效实现

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:51:34 25 4
gpt4 key购买 nike

我目前正在尝试编写一个程序,该程序将利用 RSA 或 ElGamal 等公钥密码系统。我一直在寻找不同的来源,我得到的最接近的来源是 Bouncy Castle FIPS documentation公钥加密,其中RSA的示例代码比较简单:

public byte[] pkcs1Encrypt(RSAPublicKey pubKey, byte[] data) {    
Cipher c = Cipher.getInstance(“RSA/NONE/PKCS1Padding”, “BCFIPS”);
c.init(Cipher.ENCRYPT_MODE, pubKey);
return c.doFinal(data);
}

我经常使用对称 key 密码系统,例如 AES 和 Triple-DES (DESede),但我查看了 Bouncy CaSTLe 文档,发现 RSAPublicKey 不是子- SecretKey 类的接口(interface)/类。

有什么方法可以生成这个 RSAPublicKey 对象,或者有没有更有效的方法来使用 Bouncy CaSTLe 或 JCE 实现这种加密

最佳答案

bouncycaSTLe 文档不清楚。 cipher.init(Cipher.ENCRYPT_MODE, pubKey); 需要 java.security.interfaces.RSAPublicKey 的一个实例而不是 org.bouncycastle.asn1.pkcs.RSAPublicKey

您可以使用模数和指数从 DER 编码数据构建 RSAPublicKey,或者您可以生成新的 key 对

//RSA public key from DER encoded data
byte publicKeyData[] = ...;
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyData);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey publicKey = kf.generatePublic(keySpec );

//RSA from modulus and exponent
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExponent);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey publicKey = kf.generatePublic(keySpec);

//Generate a key pair using a secure random algorithm
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(2048, random);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey privateKey = pair.getPrivate();
PublicKey publicKey = pair.getPublic();
byte publicKeyData[] = publicKey.getEncoded();

关于java - Java中RSA公钥生成和加密的有效实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539764/

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