简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM