2016-12-16 62 views
2

說我有使用OpenSSL以前創建的私有密鑰,但我已經決定不使用密碼保護它:如何在Java中的密碼添加到現有的私鑰

-----BEGIN RSA PRIVATE KEY----- 
BASE64 ENCODED DATA 
-----END RSA PRIVATE KEY----- 

但後來我意識到我想保護它。

我知道如何使用openssl來保護它,但我有要求在Java中執行它。可能嗎 ?

回答

1

首先負載並提取從PEM文件的PKCS#1未加密的密鑰

String pem = new String(Files.readAllBytes(Paths.get("rsa.key"))); 
String privateKeyPEM = pem.replace(
     "-----BEGIN RSA PRIVATE KEY-----\n", "") 
      .replace("-----END RSA PRIVATE KEY-----", ""); 
byte[] encodedPrivateKey = Base64.getDecoder().decode(privateKeyPEM); 

然後加密使用的this code第二部分中的密鑰(我已經包括它)

// 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(encodedPrivateKey); 

// 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(); 

使用以下代碼解密(從here解壓)

public static PrivateKey getPrivateKey(byte[] encryptedPkcs8, String passwd) throws Exception{ 

     EncryptedPrivateKeyInfo encryptPKInfo = new EncryptedPrivateKeyInfo(encryptedPkcs8); 

     Cipher cipher = Cipher.getInstance(encryptPKInfo.getAlgName()); 
     PBEKeySpec pbeKeySpec = new PBEKeySpec(passwd.toCharArray()); 
     SecretKeyFactory secFac = SecretKeyFactory.getInstance(encryptPKInfo.getAlgName()); 
     Key pbeKey = secFac.generateSecret(pbeKeySpec); 
     AlgorithmParameters algParams = encryptPKInfo.getAlgParameters(); 
     cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams); 
     KeySpec pkcs8KeySpec = encryptPKInfo.getKeySpec(cipher); 
     KeyFactory kf = KeyFactory.getInstance(ALGORITHM); 
     return kf.generatePrivate(pkcs8KeySpec); 
} 
+0

謝謝,但一個----- BEGIN RSA PRIVATE KEY -----標題是指pkcs8還是pkcs1格式? – TheByeByeMan

+0

你如何解密你的privateKey回來? –

+0

@GuenSeven,答案是否解決了您的問題? – pedrofb

相關問題