2011-02-26 198 views
10

我想生成口令加密的專用密鑰PKCS8格式,我嘗試使用此代碼:如何使用用密碼加密的私鑰生成RSA密鑰對?

String password = "123456"; 
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); 
gen.initialize(2048); 
KeyPair key = gen.generateKeyPair(); 
PrivateKey privateKey = key.getPrivate(); 
PublicKey publicKey = key.getPublic(); 

FileOutputStream pvt = new FileOutputStream("d:\\pvt123456.der"); 
try { 
    pvt.write(privateKey.getEncoded()); 
    pvt.flush(); 
} finally { 
    pvt.close(); 
} 
FileOutputStream pub = new FileOutputStream("d:\\pub123456.der"); 
try { 
    pub.write(publicKey.getEncoded()); 
    pub.flush(); 
} finally { 
    pub.close(); 
} 

但我不知道如何使用3DES加密密碼與OpenSSL的格式兼容。

回答

28

我知道這是一個有點晚,但我也一直在尋找一種方式來做到這一點,而我在尋找,我發現你的問題,現在我已經找到一種方法來做到這一點,我決定回來份額這樣的:

// generate key pair 

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); 
keyPairGenerator.initialize(1024); 
KeyPair keyPair = keyPairGenerator.genKeyPair(); 

// extract the encoded private key, this is an unencrypted PKCS#8 private key 
byte[] encodedprivkey = keyPair.getPrivate().getEncoded(); 

// We must use a PasswordBasedEncryption algorithm in order to encrypt the private key, you may use any common algorithm supported by openssl, you can check them in the openssl documentation http://www.openssl.org/docs/apps/pkcs8.html 
String MYPBEALG = "PBEWithSHA1AndDESede"; 
String password = "pleaseChangeit!"; 

int count = 20;// hash iteration count 
SecureRandom random = new SecureRandom(); 
byte[] salt = new byte[8]; 
random.nextBytes(salt); 

// Create PBE parameter set 
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count); 
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray()); 
SecretKeyFactory keyFac = SecretKeyFactory.getInstance(MYPBEALG); 
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); 

Cipher pbeCipher = Cipher.getInstance(MYPBEALG); 

// Initialize PBE Cipher with key and parameters 
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); 

// Encrypt the encoded Private Key with the PBE key 
byte[] ciphertext = pbeCipher.doFinal(encodedprivkey); 

// Now construct PKCS #8 EncryptedPrivateKeyInfo object 
AlgorithmParameters algparms = AlgorithmParameters.getInstance(MYPBEALG); 
algparms.init(pbeParamSpec); 
EncryptedPrivateKeyInfo encinfo = new EncryptedPrivateKeyInfo(algparms, ciphertext); 

// and here we have it! a DER encoded PKCS#8 encrypted key! 
byte[] encryptedPkcs8 = encinfo.getEncoded(); 

此示例代碼是基於如下因素代碼,我發現:http://www.jensign.com/JavaScience/PEM/EncPrivKeyInfo/EncPrivKeyInfo.java

但如下因素的資源也幫助我瞭解一個更好一點:http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/JCERefGuide.html

+7

'隨機隨機=新的隨機();'應該是'SecureRandom r andom = new SecureRandom();' – Carsten 2013-09-26 01:19:43

+0

謝謝你的建議Carsten! – Hrzio 2014-06-26 22:41:37

+1

從JDK 8中,應該使用'SecureRandom的隨機= SecureRandom.getInstanceStrong();',以確保您使用的是強大的執行由甲骨文本文檔的建議:https://docs.oracle.com/javase/tutorial /security/apisign/step2.html – CrashproofCode 2015-08-05 20:06:28