Java AES加密整个字符串 [英] Java AES Encrypt Entire String
问题描述
如何使用AES加密整个字符串?我下面的代码只能加密到第一个空格识别:(我该如何解决这个问题?谢谢
How can I encrypt an entire string with AES. The code that I have below only encrypts up to the first space recognized :(. How can I fix this? Thanks
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);
编辑
OMG我可以相信这个,我怎么可能这么简单:(其他的我的扫描器下一个而不是nextLine ...这令人尴尬的这一天让我尴尬,只有现在我才考虑检查。问题解决:)感谢大家
EDIT OMG I CANT BELIEVE THIS, HOW COULD I MISS THIS :( ITS BECAUSE MY SCANNER WAS TAKING next instead of nextLine... how embarrassing this bugged me all day and only now did i actually think about checking that. Problem solved :) Thanks everyone
推荐答案
我没有看到你的代码有任何错误,除了尝试使用新建一个任意的
。尝试这个大小: byte []
String(byte [])
I don't see anything wrong with your code except trying to print an arbitrary byte[]
using new String(byte[])
. Try this on for size:
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]
我想我们都同意这两个不同的字节数组。
I think we can all agree that those are two different byte arrays.
这篇关于Java AES加密整个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!