且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将64个字符串转换为256 AES加密的密钥

更新时间:2023-02-12 19:54:15

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 $ c>, 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.