开发者

Implement a RSA algorithm in Java

开发者 https://www.devze.com 2022-12-28 06:38 出处:网络
I want to implement a RSA algorithm to encrypt an image (byte[]). To generate my two keys I used this piece of code :

I want to implement a RSA algorithm to encrypt an image (byte[]). To generate my two keys I used this piece of code :

KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
keygen.initialize(512);
keyPair = keygen.generateKeyPair();

Once public and private key are generated, I would like to show them to the user so he can distribute the public key and use the private key to decode. How can I get back those key?

Using keygen.getPrivateKey() and keygen.getPublicKey() give me all the information of the RSA algorithm, not only the keys I need.

T开发者_开发技巧hanks


Via the Relevant KeySpec classes, you can call the getModulus() and getPublicExponent()/getPrivateExponent() methods to pull out the key components:

KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
  RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
  RSAPrivateKeySpec.class);

saveToFile("public.key", pub.getModulus(),
  pub.getPublicExponent());
saveToFile("private.key", priv.getModulus(),
  priv.getPrivateExponent());

In case it's useful, I wrote a few articles a while back dealing with some of the details of RSA encryption in Java (and Java-based cryptography generally.


What you post doesn't make any sense since getPublicKey() and getPrivateKey() return exactly what you say you need. However, if you want to extract the components you should simply cast your PublicKey and PrivateKey to RSAPublicKey and RSAPrivateKey rather than going through the rigamorole of using KeySpecs.

Also, you'll soon find out that you cannot encrypt anything larger than 501 bytes using RSA with your plan, pretty much useless for images.


You can use Key.getEncoded() to get the bytes of the key.

0

精彩评论

暂无评论...
验证码 换一张
取 消