如何将64个字符串转换为256 AES加密的密钥 [英] How to turn 64 character string into key for 256 AES encryption

查看:414
本文介绍了如何将64个字符串转换为256 AES加密的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static byte[] decryptByte(byte[] blahh, byte[] keyExample) throws Exception
{
Cipher cipher = null;

try
{
    cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
    SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKey);

    return cipher.doFinal(Base64.decodeBase64(blah));
}
catch(Exception e)
{
    e.printStackTrace();
}
return null;
}

String keyExample = "99112277445566778899AABBCCDDEEFF0123456789ABCDEF0123456789ABCDEF";
byte[] key = keyExample.getBytes();    
byte[] barrayMessage = {123,45,55,23,64,21,65};    
byte[] result = decryptByte(barrayMessage, key);

异常抛出: java.security.InvalidKeyException:AES密钥长度无效:64当你调用 String.getBytes()

Exception thrown: java.security.InvalidKeyException: Invalid AES key length: 64 bytes

推荐答案

c $ c>( JDK文档),您使用平台的默认字符集将给定字符串的字符编码为字节序列。

When you call String.getBytes() (JDK documentation) you encodes characters of the given string into a sequence of bytes using the platform's default charset.

你真正需要做的是转换每个十六进制(也是基础16)数字(由 0 9 A F code> 1A , 99 >)value eg FF - > -1 字节。

What you are actually need to do is to convert each hexadecimal (also base 16) number (represented by two characters from 0 to 9 and A to F e.g. 1A, 99, etc.) into its corresponding numerical (byte) value e.g. "FF" -> -1 byte.

示例代码如下:

Sample code is as follows:

import static java.lang.Character.digit;
...

private static byte[] stringToBytes(String input) {
    int length = input.length();
    byte[] output = new byte[length / 2];

    for (int i = 0; i < length; i += 2) {
        output[i / 2] = (byte) ((digit(input.charAt(i), 16) << 4) | digit(input.charAt(i+1), 16));
    }
    return output;
}

...

String keyExample = "99112277445566778899AABBCCDDEEFF0123456789ABCDEF0123456789ABCDEF";
byte[] key = stringToBytes(keyExample);    
byte[] barrayMessage = {123,45,55,23,64,21,65};    
byte[] result = decryptByte(barrayMessage, key);

请注意,因为我们将每两个字符转换为一个字节,输入将有偶数个字符(也是输入不是 null 和空)。

Please bear in mind that because we convert each two characters into a single byte, the proposed method assumes your input will have even number of characters (also the input is not null and empty).

如果该方法将在内部使用,那么表单是可以接受的,但如果您将它作为库的一部分对其他人可见,那么最好放一些检查并对无效输入引发异常。

If that method is going to be used internally that form is acceptable but if you make it as a part of library visible to others, it would be good to put some checks and throw exception on invalid input.

这篇关于如何将64个字符串转换为256 AES加密的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆