【Shiro】五、Apache Shiro加密

Shiro提供了更好封装,更好使用的加密算法API,可以作为平时使用的一个工具类的预选方案。

Shiro的密码学

基本特性

  接口驱动,基于POJO

  对JCE(Java Cryptography Extension)的简单封装

  面向对象的加密概念

加密特性

  接口默认实现

  内置Hex和Base64转换

  内置加盐和散列支持

编码/解码

@Test
public void testBase64(){
    String str = "hello";
    String base64Encoded = Base64.encodeToString(str.getBytes());
    String str2 = Base64.decodeToString(base64Encoded);
    Assert.assertEquals(str,str2);
}

@Test
public void testHex(){
    String str = "hello";
    String base64Encoded = Hex.encodeToString(str.getBytes());
    String str2 = new String(Hex.decode(base64Encoded.getBytes()));
    Assert.assertEquals(str, str2);
}

散列算法

普通用法

@Test
public void testMd5(){
    String str = "hello";
    String salt = "123";
    String md5 = new Md5Hash(str, salt).toString();
    System.out.println(md5);
}

@Test
public void testSha256(){
    String str = "hello";
    String salt = "123";
    String sha1= new Sha256Hash(str, salt).toString();
    System.out.println(sha1);
}

@Test
public void testSimpleHash(){
    String str = "hello";
    String salt = "123";
    String simpleHash= new SimpleHash("SHA-1", str, salt).toString();
    System.out.println(simpleHash);
}

高级用法,提供更多可配置项

 

猜你喜欢

转载自www.cnblogs.com/LiveYourLife/p/9093507.html