Cryptography is the process of hiding or obfuscating data so prying eyes can’t understand it. Shiro’s goal in cryptography is to simplify and make usable the JDK’s cryptography support.
Cryptography是隐藏或混淆数据的过程,以使窥探者无法理解它。 Shiro在Cryptography方面的目标是简化JDK的Cryptography支持并使之可用。
本系列文章目录如下:
- 为什么要使用Apache Shiro(一)
- Apache Shiro的三个重要概念(二)
- Apache Shiro核心功能之Authentication(三)
- Apache Shiro核心功能之Authorization(四)
- Apache Shiro核心功能之Session Management(五)
- Apache Shiro核心功能之Cryptography(六)
- Apache Shiro集成
- 将Apache Shiro集成到Spring-Boot应用程序中
需要注意的是,Cryptography一般不是特定于subject的,所以它是Shiro API的一个领域,不是特定于subject的。 您可以在任何地方使用Shiro的加密支持,即使没有使用Subject。
让我们更详细的看看一下两种
Hashing
JDK’s MessageDigest
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.digest(bytes);
byte[] hashed = md.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
以下是 使用 Shiro做同样的事情
String hex = new Md5Hash(myFile).toHex();
String encodedPassword =
new Sha512Hash(password, salt, count).toBase64();
Ciphers
JDK Cryptography APIs
不好用,总是在用Cipher
CipherService
Shiro试图通过引入其CipherService API来简化加密密码的整个概念。CipherService是大多数开发人员在保护数据时所需要的:一个简单的、无状态的、线程安全的API,它可以在一个方法调用中对整个数据进行加密或解密。 您所需要做的就是提供您的密钥,然后您可以根据需要加密或解密。
Apache Shiro’s 256-bit AES Encryption API
AesCipherService cipherService = new AesCipherService();
cipherService.setKeySize(256);
//create a test key:
byte[] testKey = cipherService.generateNewKey();
//encrypt a file’s bytes:
byte[] encrypted = cipherService.encrypt(fileBytes, testKey);