我正在我的应用程序中实现 SSL 证书和密钥。我使用 CertAndKeyGen 类创建了私钥。我正在尝试使用密码加密私钥,这是我通过 PBE 和 Cipher 类实现的。我想将加密的私钥写入 PEM 格式的文件中。我尝试使用正在工作的 FileOutputStream,但 PrintWriter 无法正常工作。
下面是我的代码,
final CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
keypair.generate(1024);
final PrivateKey privKey = keypair.getPrivateKey();
byte[] encodedprivkey = privKey.getEncoded();
String MYPBEALG = "PBEWithSHA1AndDESede";
String password = "test123";
int count = 20;// hash iteration count
Random random = new Random();
byte[] salt = new byte[8];
random.nextBytes(salt);
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);
byte[] encryptedPkcs8 = encinfo.getEncoded();
// Now I am writing the encrypted private key into a file.
// Using FileOutputStream
FileOutputStream out = new FileOutputStream("usingOutEncrypedPrivkey");
out.write(Base64.encodeBase64(encryptedPkcs8, true));
out.flush();
out.close();
// Using PrintWriter
PrintWriter pw = new PrintWriter("usingPwEncryptedPrivKey");
pw.println("-----BEGIN "+ privKey.getAlgorithm() + " PRIVATE KEY-----");
pw.println(Base64.encodeBase64(encryptedPkcs8));
pw.println("-----END "+ privKey.getAlgorithm() +" PRIVATE KEY-----");
pw.close();
以下是保存的文件,
usingOutEncrypedPrivkey // Which was saved using FileOutputStream
MIICoTAbBgoqhkiG9w0BDAEDMA0ECL4xgraq2hXxAgEUBIICgFENaB8EA/kR0ymSC8vcyj1fNFbP
iR+mXkBk7aH3eF7fpP8yqCvtN0/0VqHi/w/Z2CLgiib2s/zuiVPtWI8vsRRPXmD9PYxZp3ilLpD4
.....
.....
9nH8HdQf584c3sKYEErDQvJR2SmbUPtNq4cB6ocUuiOTztBqRXAHeaWavnqHFxHUT7c=
usingPwEncryptedPrivKey // Which was saved using PrintWriter
-----BEGIN RSA PRIVATE KEY-----
[B@19e3118a
-----END RSA PRIVATE KEY-----
为什么 PrintWriter 写为“[B@19e3118a”,而不是像 FileOutputStream 这样的字节。我想使用 PrintWriter 因为我想使用 PrintWriter.println() 函数。请帮帮我。提前致谢。