【问题标题】:Java AES Encrypt Entire StringJava AES 加密整个字符串
【发布时间】:2011-12-08 13:01:23
【问题描述】:

如何使用 AES 加密整个字符串。我下面的代码只加密到第一个识别的空间:(。我该如何解决这个问题?谢谢

SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    String result = new String(cipher.doFinal(message.getBytes()));
    System.out.println("Encrypted:" + result);

编辑 天哪,我不敢相信,我怎么会错过这个:(这是因为我的扫描仪正在使用 next 而不是 nextLine ......这让我一整天都感到尴尬,直到现在我才真正考虑检查它。问题解决了 :) 谢谢大家

【问题讨论】:

  • 例子加密的“hello world”和“hello”都是“sÀÊç$û?dgÞÏ┌q°(Ô,当salt为“1111111111111111”时
  • 不要将加密的字符串数据视为字符串 - 不是。 如果您想获得人类可读的表示,请将字符串转换为 base64 或十六进制字符串,然后打印出来。
  • 这就是我错过其余消息的原因吗?如果它是人类可读的,它对我的​​影响并不大,事实上,如果不是,我可能更喜欢它:)
  • @Matt - 哦。好的,我会删除我的评论并为你的回答 +1。
  • 不要使用 ECB 模式。它很弱。至少使用 CBC,或者最好是经过身份验证的模式。

标签: java string encryption aes


【解决方案1】:

除了尝试使用new String(byte[]) 打印任意byte[] 之外,我没有发现您的代码有任何问题。试穿这个尺寸:

public static byte[] encrypt(String message) throws Exception
{
    String salt = "1111111111111111";
    SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return cipher.doFinal(message.getBytes());
}

public static void main (String[] args) throws Exception
{
    String hello = Arrays.toString(encrypt("hello"));
    System.out.println("hello:" + hello);
    String helloWorld = Arrays.toString(encrypt("hello world"));
    System.out.println("hello world:" + helloWorld);
}

哪些打印:

hello:[115, -73, -46, -121, 36, -106, -99, 100, 103, -24, -40, -38, 113, -8, 40, -57]
hello world:[5, 88, -31, 115, 4, 48, -75, 44, 83, 21, 105, -67, 78, -53, -13, -28]

我想我们都同意这是两个不同的字节数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多