在 Java 中有效实施 RSA Public 密钥生成和加密

Effective Implementation of RSA Public Key Generation and Encryption in Java

我目前正在尝试编写一个程序,该程序将利用 public 密钥密码系统,例如 RSA 或 ElGamal。我一直在寻找不同的来源,我得到的最接近的是 public 密钥加密的 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);
} 

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

有没有办法生成这个 RSAPublicKey 对象,或者有没有更有效的方法来使用 Bouncy Castle 或 JCE 实现这种加密

bouncycastle文档不清楚。 cipher.init(Cipher.ENCRYPT_MODE, pubKey); 需要 java.security.interfaces.RSAPublicKey and not 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();