简体   繁体   English

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

[英]Effective Implementation of RSA Public Key Generation and Encryption in Java

I am currently trying to write a program that will utilize a public key cryptosystem such as RSA or ElGamal. 我目前正在尝试编写一个程序,该程序将使用RSA或ElGamal等公钥密码系统。 I have been looking at different sources, and the closest I have gotten was in the Bouncy Castle FIPS documentation of public key encryption, where the sample code for RSA is somewhat simple: 我一直在寻找不同的来源,我得到的最接近的是公钥加密的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);
} 

I've worked often with symmetric key cryptosystems such as AES and Triple-DES (DESede), but I looked under the Bouncy Castle documentation, and found out that the RSAPublicKey is not a sub-interface/class of the SecretKey class. 我经常使用对称密钥密码系统,如AES和Triple-DES(DESede),但我查看了Bouncy Castle文档,发现RSAPublicKey不是SecretKey类的子接口/类。

Is there any way to generate this RSAPublicKey object, or is there a more efficient way to implement this kind of encryption with Bouncy Castle or the JCE 有没有办法生成这个RSAPublicKey对象,或者有更有效的方法来实现这种加密与Bouncy Castle或JCE

The bouncycastle document is not clear. 这个双胞胎文件不清楚。 cipher.init(Cipher.ENCRYPT_MODE, pubKey); requires an instance of java.security.interfaces.RSAPublicKey and not org.bouncycastle.asn1.pkcs.RSAPublicKey 需要一个java.security.interfaces.RSAPublicKey实例而不是org.bouncycastle.asn1.pkcs.RSAPublicKey

You can build RSAPublicKey using modulus and exponent, from the DER encoded data, or you can generate a new key pair 您可以使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM