此代碼生成一對公鑰/私鑰:Java的非對稱加密:存儲公/私鑰
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair keypair = keyGen.genKeyPair();
PrivateKey privateKey = keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
我想知道什麼是你通常如何保存的公鑰:
選項1:存儲字節
byte[] privateKeyBytes = privateKey.getEncoded();
byte[] publicKeyBytes = publicKey.getEncoded();
// ... write to file
// convert bytes back to public/private keys
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
我不喜歡的是將代碼綁定到具體的實現,例如PKCS8EncodedKeySpec
和X509EncodedKeySpec
。
選項2:存儲係數和指數
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(publicKey, RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(privateKey,RSAPrivateKeySpec.class);
// store modulus and exponent as BigIntegers
BigInteger modulus = pub.getModulus());
BigInteger exponent = pub.getPublicExponent());
// ... write to file
// recreate public key (the same applies to the private key)
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
第二個選項是更容易實現,但我不知道這是否可能是少高性能。
有沒有建議嗎?
DER是不是一個真正的格式本身,只是編碼ASN.1對象 – 2010-08-09 21:37:21
對於那些希望獲得'公共的方式。直接從'id_rsa.pub'(公鑰),而不是'id_rsa'(私鑰)der' [這個答案提供了一種方法來做到這一點(http://stackoverflow.com/a/18290786/813810)。 – Diego 2014-09-01 10:54:01