Getting a secret key using a master key using JCE / JCA

Can someone point me in the right direction?

I would like to use JCE / JCA to get a new key from the master secret key. How can i do this?

Sincerely.

+4
source share
1 answer

JCA provides standard password-based key output functions, such as PBKDF2, defined in PKCS # 5 v2.0 and RFC 2898 . This algorithm creates some random material from the master secret (password) to create a key suitable for the given cipher.

public byte[] deriveKey(String password, byte[] salt, int keyLen) { SecretKeyFactory kf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec specs = new PBEKeySpec(password.toCharArray(), salt, 1024, keyLen); SecretKey key = kf.generateSecret(specs); return key.getEncoded(); } public byte[] encrypt(String password, byte[] plaintext) { byte[] salt = new byte[64]; Random rnd = new Random(); rnd.nextByte(salt); byte[] data = deriveKey(password, salt, 192); SecretKey desKey = SecretKeyFactory.getInstance("DESede").generateSecret(new DESedeKeySpec(data)); Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, desKey); return cipher.doFinal(plaintext); } 
+5
source

Source: https://habr.com/ru/post/1204342/


All Articles