在 Java 中有效实现 RSA 公钥生成和加密



我目前正在尝试编写一个利用公钥密码系统(如RSA或ElGamal)的程序。 我一直在查看不同的来源,我得到的最接近的是公钥加密的Bouncy Castle FIPS文档,其中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);
} 

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

有没有办法生成这个RSAPublicKey对象,或者有没有更有效的方法来实现这种加密与充气城堡或JCE的

加密

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

您可以使用模数和指数从 DER 编码数据构建RSAPublicKey,也可以生成新的密钥对

//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();

最新更新