1

how do I encrypt a private key created using the KeyPairGenerator in java with scrypt? I want to secure the private key using a password, so no one can use the private key to decrypt the data I encrypted even if he has the private key and the data. (I'd use the BouncyCastle API, if you don't propose any other)

Thanks

Nightloewe
  • 918
  • 1
  • 14
  • 24
  • Put it into a `Keystore`. That's what they're for. – user207421 Nov 15 '19 at 08:31
  • I'm not aware of any convenient support for scrypt in private key protection, in Bouncycastle or any other library. However, PKCS#12 and PKCS#8 both support a good alternative in PBKDF2. PBKDF2 is probably not as good as an scrypt-based solution but it's still pretty good. And PKCS#12 is now the preferred format for Java keystores so, as the previous comment suggests, that is likely the way to go. – President James K. Polk Nov 15 '19 at 13:43

1 Answers1

1

To use KeyPairGenerator, you can encrypt the password-backed private key by using PBEKey and Parameters

KeyPairGenerator generator = KeyPairGenerator.getInstance();

int count = 5;

keyPairGenerator.initialize();
KeyPair kPair = generator.genKeyPair();

byte[] privateKey = kPair.getPrivate().getEncoded();

String stringPb = "PBEWithSHA1AndDESede";
String password = "your_own_password";

SecureRandom rndm = new SecureRandom();

PBEParameterSpec paramSpec = new PBEParameterSpec(salt, count);
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());

SecretKeyFactory factory = SecretKeyFactory.getInstance();
SecretKey pbeKey = factory.generateSecret(keySpec);

Cipher cipher = Cipher.getInstance(stringPb);

cipher.init(ENCRYPT_MODE, pbeKey, paramSpec);

byte[] text = cipher.doFinal();

AlgorithmParameters parametres = AlgorithmParameters.getInstance();
parametres.init(paramSpec);
EncryptedPrivateKeyInfo encinfo = new EncryptedPrivateKeyInfo(parametres, text);
marcoreus
  • 36
  • 1
  • 7