加密,解密,shiro用法測試
阿新 • • 發佈:2018-12-10
在shiro授權和認證中,我們經常用到資料的加密和解密,這裡做了一些資料的加密方法的測試
1、新增依賴
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.0</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency>
2、編寫測試程式碼
package test; import org.apache.shiro.codec.Base64; import org.apache.shiro.codec.Hex; import org.apache.shiro.crypto.hash.*; import org.junit.Test; /** * @author 大宇 * @create 2018/12/10 21:12 * Description 加密、解密 */ public class EncryptTest {//加密內容 private String pass = "encryptString"; //鹽 private String salt = "salt"; //加密次數 private int hashIterations = 10; /** * base64 */ @Test public void test1() { String encodeToString = Base64.encodeToString(pass.getBytes()); System.out.println(encodeToString); String decodeToString = new String(Base64.decodeToString(pass)); System.out.println(decodeToString); } /** * md5加密 */ @Test public void test2() { //MD5普通加密 String encodeToString = new Md5Hash(pass).toString(); System.out.println(encodeToString); //md5加密轉base64位編碼或者16進位制編碼 String md5Base64 = new Md5Hash(pass).toBase64(); String md5Hex = new Md5Hash(pass).toHex(); System.out.println(md5Base64); System.out.println(md5Hex); //md5加密,加密內容source,帶鹽加密salt,還可以指定加密次數:hashIterations md5Base64 = new Md5Hash("asdf", "123", 5).toBase64(); System.out.println(md5Base64); } /** * sha加密 * SHA1,SHA256,SHA512 */ @Test public void test3() { String sha1hash = new Sha1Hash(pass, salt, hashIterations).toBase64(); String sha256hash = new Sha256Hash(pass, salt, hashIterations).toBase64(); String sha512hash = new Sha512Hash(pass, salt, hashIterations).toBase64(); System.out.println(sha1hash); System.out.println(sha256hash); System.out.println(sha512hash); } /** * 通用加密:SimpleHash,將演算法名稱新增到方法即可 */ @Test public void testSimleHash() { // algorithmName 演算法名稱 String algorithmName="md5";//sha1,sha-256,sha-512。。。,下面的第一個引數 String encryptStr = new SimpleHash("md5", pass, salt, hashIterations).toBase64(); String sha256 = new SimpleHash("sha-256", pass, salt, hashIterations).toBase64(); String sha512= new SimpleHash("sha-512", pass, salt, hashIterations).toBase64(); System.out.println(encryptStr); System.out.println(sha256); System.out.println(sha512); } //hex十六進位制編碼 @Test public void testHex() { String encodeToString = Hex.encodeToString(pass.getBytes()); String decodeToString = new String(Hex.decode(encodeToString)); System.out.println("加密:"+encodeToString); System.out.println("解密:"+decodeToString); } }
通常,我們儲存使用者的賬號密碼都應該使用不可逆的加密方式,用來防賬號洩露帶來的風險,而不是可逆的加密方式