【问题标题】:Java AES 256 encryptionJava AES 256 加密
【发布时间】:2014-02-06 23:01:23
【问题描述】:

我有下面的 java 代码来加密一个使用 64 字符密钥的字符串。我的问题是这将是 AES-256 加密吗?

String keyString = "C0BAE23DF8B51807B3E17D21925FADF273A70181E1D81B8EDE6C76A5C1F1716E";
byte[] keyValue = hexStringToByte(keyString);
Key key = new SecretKeySpec(keyValue, "AES");
Cipher c1 = Cipher.getInstance("AES");
c1.init(Cipher.ENCRYPT_MODE, key);

String data = "Some data to encrypt";
byte[] encVal = c1.doFinal(data.getBytes());
String encryptedValue = Base64.encodeBase64String(encVal);


/* Copied the below code from another post in stackexchange */
public static byte[] hexStringToByte(String hexstr) 
{
  byte[] retVal = new BigInteger(hexstr, 16).toByteArray();
  if (retVal[0] == 0) 
  {
    byte[] newArray = new byte[retVal.length - 1];
    System.arraycopy(retVal, 1, newArray, 0, newArray.length);
    return newArray;
  }
  return retVal;
}

以下是合并divanov和laz的建议后的代码。

String keyString = "C0BAE23DF8B51807B3E17D21925FADF273A70181E1D81B8EDE6C76A5C1F1716E";
byte[] keyValue = DatatypeConverter.parseHexBinary(keyString);
Key key = new SecretKeySpec(keyValue, "AES");
Cipher c1 = Cipher.getInstance("AES");
c1.init(Cipher.ENCRYPT_MODE, key);

String data = "Some data to encrypt";
byte[] encVal = c1.doFinal(data.getBytes());
String encryptedValue = Base64.encodeBase64String(encVal);

【问题讨论】:

  • 这个问题似乎是在询问 PBE 派生的 AES 密钥。
  • 执行不正确十六进制解码的帖子在哪里?我迫切需要对它投反对票。

标签: java aes encryption


【解决方案1】:

是的,因为 64 个字符是 32 字节和 256 位,任何 256 位序列都可以用作 AES-256 密钥。

我建议您使用DatatypeConverter.parseHexBinary(或您选择的库中的类似实用程序)将十六进制字符串转换为字节数组。

【讨论】:

  • 真的吗?你看到byte[] new = new byte[retVal.length - 1];了吗?
  • 这是处理 BigInteger 附加的符号字节的笨拙尝试。
  • DatatypeConverter 也是用于解码十六进制字符串的主要 Java API 的一部分:docs.oracle.com/javase/7/docs/api/javax/xml/bind/…
猜你喜欢
  • 2013-08-24
  • 1970-01-01
  • 1970-01-01
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
  • 2010-11-02
  • 2020-01-20
相关资源
最近更新 更多