Java Apache Shiro AES加密与预期输出不同
我正在使用ApacheShiro提供的Java Apache Shiro AES加密与预期输出不同,java,encryption,shiro,Java,Encryption,Shiro,我正在使用ApacheShiro提供的AesCipherService 由于某种原因,我不能让它像这样工作 我的代码基本上是这样的: String encrypt(String input) throws Exception { StringBuilder builder = new StringBuilder(); AesCipherService aesCipher = new AesCipherService(); byte[] bytes = aesCipher
AesCipherService
由于某种原因,我不能让它像这样工作
我的代码基本上是这样的:
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);
}
如果你加密“你好”,你会得到
Shvvv71GB++/vULvv73vv71/Zu+/vRIc77+977+9Y33bkmrvv70SOWffqXTvv71777+977+9
当该站点输出
IM/5UIbDXWhuPz2ZFKyScQ==
我对代码做了什么错误?看起来您可能不止一次地进行了Base 64编码。此外,它使用“ECB”模式,这不是密码中的默认模式。因此,您看到了输出的差异。重要的是,加密和解密使用相同的算法 下面是更正的代码
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==
注意:这与为相同输入生成的内容不同,但是,可以在上解密此字符串。我不确定造成这种差异的原因是什么
b64 xqkuF4FDmucSdb410R0HPw==hex c6a92e17 81439ae7 1275be35 d11d073f使用11字节0x0B pck#5/7填充解密为ASCII“Hello”,这是real Java(JCE)默认的做法,我猜shiro也会这样做。b64 IM/5UIbDXWhuPz2ZFKyScQ==十六进制20cff950 86c35d68 6e3f3d99 14ac9271使用零填充解密为ASCII“Hello”。该网站上的介绍性文字向我建议,他们使用PHP加密,而PHP加密因使用不安全的零填充而臭名昭著;只需搜索security.SE。