Java AES加密整个字符串

3

我如何使用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... 真是太尴尬了,这个问题困扰了我一整天,直到现在我才想起来检查它。问题解决 :) 谢谢大家


例如,当盐值为“1111111111111111”时,加密后的“hello world”和“hello”都是“sÀÊç$û?dgÞÏ┌q°(Ô。 - Cody
3
不要将加密的字符串数据视为字符串 - 它不是字符串。如果您想获取可读的人类表示形式,请将字符串转换为base64或十六进制字符串,然后打印它。 - Matt Ball
这就是我错过了消息的原因吗?而且它对我影响不大,无论它是否可读,事实上,如果它不可读,我可能更喜欢它 :) - Cody
@Matt - 哦。好的,我会删除我的评论并点赞你的回答。 - kdgregory
不要使用ECB模式,它非常薄弱。至少使用CBC,或者最好使用认证模式。 - CodesInChaos
1个回答

6

除了尝试使用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]

我认为我们都可以同意这是两个不同的字节数组。

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