編碼與解碼
Shiro 提供了 base64 和 16 進制字符串編碼、解碼的 API 支持,方便一些編碼解碼操作。Shiro 內部的一些數據的存儲 、表示都使用了 base64 和 16 進制字符串。
1、base64 編碼與解碼
String str = "admin";
String base64Encoded = Base64.encodeToString(str.getBytes());
String str2 = Base64.decodeToString(base64Encoded);
logger.info(str+"<==="+base64Encoded+"==>"+str2);
2、16 進制字符串編碼與解碼
String str3 = "test";
String hexEncoded2 = Hex.encodeToString(str3.getBytes());
String str4 = new String(Hex.decode(hexEncoded2.getBytes()));
logger.info(str3+"<==="+hexEncoded2+"==>"+str4);
散列算法加密
散列算法一般用於生成數據的重要信息,是一種不可逆的算法,適合存儲密碼之類的數據,常見的散列算法如 MD5、SHA 等。
1、 MD5算法鹽值加密
String pswd= "123456";
String salt = "123";
String md5 = new Md5Hash(pswd, salt).toString();
另外散列時還可以指定散列次數,new Md5Hash(pswd, salt, 2).toString(),數字2代表加密次數。
2、 SHA256 算法鹽值加密
String pswd= "123456";
String salt = "123";
String sha = new Sha256Hash(pswd, salt).toString();
3、 SHA1算法鹽值加密
String pswd= "123456";
String salt = "123";
String sha = new Sha1Hash(pswd, salt).toString();
4、SHA512算法鹽值加密
String pswd = "123456";
String salt = "123";
String sha = new Sha512Hash(pswd, salt).toString();
5、 Shiro 還提供了通用的散列SimpleHash
String pswd = "123456";
String salt = "123";
//內部使用MessageDigest
String simpleHash=
new SimpleHash("SHA-1",pswd,salt,4).toString();
Shiro 還提供對稱式加密、解密算法的支持
1、 AES 算法
//生成key
Key key = aesCipherService.generateNewKey();
String pswd = "123456";
//加密
String encrptText = aesCipherService.encrypt(pswd.getBytes(), key.getEncoded()).toHex();
//解密
String text2 =
new String(aesCipherService.decrypt(Hex.decode(encrptText), key.getEncoded()).getBytes());
logger.info(pswd+"<==="+encrptText+"==>"+text2);
簡單模擬用戶註冊
1、首先使用SHA256算法加密密碼明文,UserService層實現。
UserDaoImpl userDaoimpl ;
public static void main(String[] args) {
String email ="[email protected]";
String password = "123";
String sha = new Sha256Hash(password, ByteSource.Util.bytes(email)).toString();//使用郵箱作為鹽值
User user = new User(4L,"管理員",email,sha,new Date(),new Date(),1);
UserService userService = new UserService();
userService.insert(user);
}
public int insert(User user){
userDaoimpl =new UserDaoImpl();
return userDaoimpl.insert(user);
}
2、Dao插入數據
@Override
public int insert(User record) {
String sql = "insert into u_user(id,nickname,email,pswd,create_time,last_login_time,status) values (?,?,?,?,?,?,?)";
return insert(sql,record.getId(),record.getNickname(),record.getEmail(),record.getPswd(),record.getCreateTime(),record.getLastLoginTime(),record.getStatus());
}
HashedCredentialsMatcher 實現密碼驗證服務
1、 自定義JdbcRealm實現AuthorizingRealm接口,重寫doGetAuthenticationInfo(,,,)方法。
2、 配置ini文件內容
主要配置HashedCredentialsMatcher實現密碼驗證服務。
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
credentialsMatcher.hashAlgorithmName=SHA-256#加密算法
credentialsMatcher.hashIterations=1#迭代次數
credentialsMatcher.storedCredentialsHexEncoded=true
jdbcRealm=com.shiro.test.JdbcRealm
jdbcRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$jdbcRealm
3、 用郵箱、密碼實現登錄認證
4、結果