Apache Shiro AES 加密与预期输出不同
Apache Shiro AES encryption differs from expected output
我正在使用来自 Apache Shiro 的 AesCipherService
。
出于某种原因,我无法让它像 http://aesencryption.net/ 那样工作。
我的代码基本上是这样的:
String encrypt(String input) throws Exception {
StringBuilder builder = new StringBuilder();
AesCipherService aesCipher = new AesCipherService();
byte[] bytes = aesCipher.encrypt(input.getBytes(), "0123456789abcdef".getBytes()).getBytes();
String aesProduct = new String(bytes);
builder.append(aesProduct);
byte[] bytesEncoded = Base64.encodeBase64(builder.toString().getBytes());
return new String(bytesEncoded);
}
如果你加密"Hello"你会得到
Shvvv71GB++/vULvv73vv71/Zu+/vRIc77+977+9Y33bkmrvv70SOWffqXTvv71777+977+9
当该站点输出时
IM/5UIbDXWhuPz2ZFKyScQ==
我的代码做错了什么?
看来您可能不止一次进行 Base 64 编码。此外,site 使用 "ECB" 模式,这不是 Cipher 中的默认模式。因此,您会看到输出的差异。加密和解密使用相同的算法很重要。
以下是更正后的代码。
import org.apache.commons.codec.binary.Base64;
import org.apache.shiro.crypto.AesCipherService;
public class Test {
public static void main(String[] args) throws Exception {
System.out.println(encrypt("Hello"));
}
static String encrypt(String input) throws Exception {
AesCipherService aesCipher = new AesCipherService();
aesCipher.setModeName("ECB");
byte[] bytes = aesCipher.encrypt(input.getBytes("UTF-8"), "0123456789abcdef".getBytes()).getBytes();
byte[] bytesEncoded = Base64.encodeBase64(bytes);
return new String(bytesEncoded);
}
}
这会产生
xqkuF4FDmucSdb410R0HPw==
注意: 这与 site 为相同输入生成的内容不同,但是,可以在 site 上解密此字符串。我不确定差异的原因是什么。
我正在使用来自 Apache Shiro 的 AesCipherService
。
出于某种原因,我无法让它像 http://aesencryption.net/ 那样工作。
我的代码基本上是这样的:
String encrypt(String input) throws Exception {
StringBuilder builder = new StringBuilder();
AesCipherService aesCipher = new AesCipherService();
byte[] bytes = aesCipher.encrypt(input.getBytes(), "0123456789abcdef".getBytes()).getBytes();
String aesProduct = new String(bytes);
builder.append(aesProduct);
byte[] bytesEncoded = Base64.encodeBase64(builder.toString().getBytes());
return new String(bytesEncoded);
}
如果你加密"Hello"你会得到
Shvvv71GB++/vULvv73vv71/Zu+/vRIc77+977+9Y33bkmrvv70SOWffqXTvv71777+977+9
当该站点输出时
IM/5UIbDXWhuPz2ZFKyScQ==
我的代码做错了什么?
看来您可能不止一次进行 Base 64 编码。此外,site 使用 "ECB" 模式,这不是 Cipher 中的默认模式。因此,您会看到输出的差异。加密和解密使用相同的算法很重要。
以下是更正后的代码。
import org.apache.commons.codec.binary.Base64;
import org.apache.shiro.crypto.AesCipherService;
public class Test {
public static void main(String[] args) throws Exception {
System.out.println(encrypt("Hello"));
}
static String encrypt(String input) throws Exception {
AesCipherService aesCipher = new AesCipherService();
aesCipher.setModeName("ECB");
byte[] bytes = aesCipher.encrypt(input.getBytes("UTF-8"), "0123456789abcdef".getBytes()).getBytes();
byte[] bytesEncoded = Base64.encodeBase64(bytes);
return new String(bytesEncoded);
}
}
这会产生
xqkuF4FDmucSdb410R0HPw==
注意: 这与 site 为相同输入生成的内容不同,但是,可以在 site 上解密此字符串。我不确定差异的原因是什么。