Nightloewe
Nightloewe

Reputation: 1098

How do I use scrypt to encrypt a private key with a password

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

Upvotes: 1

Views: 415

Answers (1)

marcoreus
marcoreus

Reputation: 36

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

Upvotes: 1

Related Questions