简体   繁体   English

Java AES加密整个字符串

[英]Java AES Encrypt Entire String

How can I encrypt an entire string with AES. 如何使用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);

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 编辑 OMG我不相信这一点,我怎么可能想念这个:(因为我的扫描仪接下来而不是nextLine ...这整天都让我感到尴尬,但是现在才真正考虑检查那个问题。问题解决了:)谢谢大家

I don't see anything wrong with your code except trying to print an arbitrary byte[] using new String(byte[]) . 除了尝试使用new String(byte[])打印任意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);
}

Which prints: 哪个印刷品:

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. 我想我们都同意这些是两个不同的字节数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM