简体   繁体   中英

PBKDF2WithHmacSHA1 confusing

Can anybody tell me what is the use of 128*8 in the code below? I have written the code for password encryption and I still don't know what this 128*8 is doing.

This is what I get as a return from this code:

67a0759ac6266ca2156555426aae10b18c34b436ea036247e6c0e16cd8d4199b9df508c32cd14e50a533ac00c071888cb8167982d9bf22a89ccd1c02a9d9c76d4e5fb5c3be91711a444a3b453c54790d5b540d7f3d0ef5798cf6a08e5acaf1b0fb445e174befd2e5b97978534aa7c22c4e404503e40f06f6832fe4a5843c9b01

The toHex() function is below: I think returned values are in characters.

private static String toHex(byte[] array) throws NoSuchAlgorithmException
    {
        BigInteger bi = new BigInteger(1, array);
        String hex = bi.toString(16);
        int paddingLength = (array.length * 2) - hex.length();
        if(paddingLength > 0)
        {
            return String.format("%0"  +paddingLength + "d", 0) + hex;
        }else{
            return hex;
        }
    }



public static String encrypt(String password,String key) throws NoSuchAlgorithmException, InvalidKeySpecException {

       int iterations = 4096;
        char[] chars = password.toCharArray();
        byte[] salt = key.getBytes();

        PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 128 * 8);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] hash = skf.generateSecret(spec).getEncoded();
        return toHex(hash);
    }

The 128*8 is the requested key length, as per the documentation .

keyLength - the to-be-derived key length.

It's not clear that it's in bits, but it is. So you're asking for a key which is 1024 bits long (because 128 * 8 = 1024).

You're getting back a hex representation which is 256 characters long, each of which is a hex digit. A single hex digit encodes 4 bits, so you've got a key which is 1024 bits long, just as you asked for.

The 4th parameter is the key length

PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength)

Constructor that takes a password, salt, iteration count, and to-be-derived key length for generating PBEKey of variable-key-size PBE ciphers.

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