如何生成一个用于AES算法的128位密钥

3
我正在使用下面提到的帖子中的代码,在我的应用程序的Java和JavaScript模块之间加密和解密值。 Java和Javascript兼容的AES算法 在上面的帖子中,他们使用128位密钥值。我想使用自己的密钥而不是硬编码128位密钥值。
我的问题是,我能否将任何随机字符串转换为128位密钥值。
如果可以将任何字符串转换为128位值,请提供一些示例。

2个回答

7

2

我通过Google发现了一些内容,并在我的项目中使用:

private final static String algorithm = "PBKDF2WithHmacSHA1";

private final static String HEX = "0123456789ABCDEF";

private static final String CP_ALGORITH = "AES";
private static final String CP_KEY = "PUTsomeKEYinHere";

public static String cipher(String cipherKey, String data) throws NoSuchAlgorithmException, 
                    InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, 
                    IllegalBlockSizeException, BadPaddingException {
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
    KeySpec spec = new PBEKeySpec(cipherKey.toCharArray(), cipherKey.getBytes(), 128, 256);
    SecretKey tmp = skf.generateSecret(spec);
    SecretKey key = new SecretKeySpec(tmp.getEncoded(), CP_ALGORITH);
    Cipher cipher = Cipher.getInstance(CP_ALGORITH);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return toHex(cipher.doFinal(data.getBytes()));
}

public static String decipher(String cipherKey, String data) throws NoSuchAlgorithmException, 
                        InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, 
                        IllegalBlockSizeException, BadPaddingException {
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
    KeySpec spec = new PBEKeySpec(cipherKey.toCharArray(), cipherKey.getBytes(), 128, 256);
    SecretKey tmp = skf.generateSecret(spec);
    SecretKey key = new SecretKeySpec(tmp.getEncoded(), CP_ALGORITH);
    Cipher cipher = Cipher.getInstance(CP_ALGORITH);
    cipher.init(Cipher.DECRYPT_MODE, key);
    return new String(cipher.doFinal(toByte(data)));
}

private static byte[] toByte(String data) throws NullPointerException{
    int len = data.length()/2;
    byte[] result = new byte[len];
    for (int i = 0; i < len; i++)
        result[i] = Integer.valueOf(data.substring(2*i, 2*i+2), 16).byteValue();
    return result;
}

private static String toHex(byte[] doFinal) {
    StringBuffer result = new StringBuffer(2*doFinal.length);
    for (int i = 0; i < doFinal.length; i++) {
        result.append(HEX.charAt((doFinal[i]>>4)&0x0f)).append(HEX.charAt(doFinal[i]&0x0f));
    }
    return result.toString();
}

使用方法:

cipher(CP_KEY, STRINGtoCIPHER);

decipher(CP_KEY, YOURcipheredSTRING)

我把这些都放在一个带有静态字段和方法的共享类中,这样我就可以在应用程序中的任何地方使用它了。我用它来存储我在共享首选项中的SessionID,并且它运行良好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接