在Java

时间:2017-01-09 01:27:09

标签: java cryptography rsa bouncycastle

我目前正在尝试编写一个利用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);
} 

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

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

1 个答案:

答案 0 :(得分:1)

bouncycastle文件不清楚。 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();