• 编码和加密


    Shiro提供了base64和16进制字符串编码/解码的API支持,方便一些编码解码操作。Shiro内部的一些数据的存储/表示都使用了base64和16进制字符串。

        String str = "hello";  
        String base64Encoded = Base64.encodeToString(str.getBytes());  
        String str2 = Base64.decodeToString(base64Encoded);  
        Assert.assertEquals(str, str2);   
    
        String str = "hello";  
        String base64Encoded = Hex.encodeToString(str.getBytes());  
        String str2 = new String(Hex.decode(base64Encoded.getBytes()));  
        Assert.assertEquals(str, str2);   
    

     散列算法

    散列算法一般用于生成数据的摘要信息,是一种不可逆的算法,一般适合存储密码之类的数据,常见的散列算法如MD5、SHA等。一般进行散列时最好提供一个salt(盐),比如加密密码“admin”,产生的散列值是“21232f297a57a5a743894a0e4a801fc3”,可以到一些md5解密网站很容易的通过散列值得到密码“admin”,即如果直接对密码进行散列相对来说破解更容易,此时我们可以加一些只有系统知道的干扰数据,如用户名和ID(即盐);这样散列的对象是“密码+用户名+ID”,这样生成的散列值相对来说更难破解。

    String str = "hello";  
    String salt = "123";  
    String md5 = new Md5Hash(str, salt).toString();//还可以转换为 toBase64()/toHex() 
    

     如上代码通过盐“123”MD5散列“hello”。另外散列时还可以指定散列次数,如2次表示:md5(md5(str)):“new Md5Hash(str, salt, 2).toString()”。

    String str = "hello";  
    String salt = "123";  
    String sha1 = new Sha256Hash(str, salt).toString();  
    

     使用SHA256算法生成相应的散列数据,另外还有如SHA1SHA512算法。 

    Shiro还提供了通用的散列支持:

        String str = "hello";  
        String salt = "123";  
        //内部使用MessageDigest  
        String simpleHash = new SimpleHash("SHA-1", str, salt).toString();   
    

    加密/解密

    Shiro还提供对称式加密/解密算法的支持,如AES、Blowfish等;当前还没有提供对非对称加密/解密算法支持,未来版本可能提供。

        AesCipherService aesCipherService = new AesCipherService();  
        aesCipherService.setKeySize(128); //设置key长度  
        //生成key  
        Key key = aesCipherService.generateNewKey();  
        String text = "hello";  
        //加密  
        String encrptText =   
        aesCipherService.encrypt(text.getBytes(), key.getEncoded()).toHex();  
        //解密  
        String text2 =  
         new String(aesCipherService.decrypt(Hex.decode(encrptText), key.getEncoded()).getBytes());  
          
        Assert.assertEquals(text, text2);   
    

    生成密码散列值

    String algorithmName = "md5";  
    String username = "liu";  
    String password = "123";  
    String salt1 = username;  
    String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();  
    int hashIterations = 2;  
      
    SimpleHash hash = new SimpleHash(algorithmName, password, salt1 + salt2, hashIterations);  
    String encodedPassword = hash.toHex();  
    

     如果要写用户模块,需要在新增用户/重置密码时使用如上算法保存密码,将生成的密码及salt2存入数据库(因为我们的散列算法是:md5(md5(密码+username+salt2)))。

  • 相关阅读:
    存储与服务器的连接方式对比(DAS,NAS,SAN)
    FreeNAS系统总结
    FreeNAS-9.10虚拟机测试安装
    rsync实时同步服务部署
    无限循环与嵌套循环
    几种循环语句
    选择结构if
    java引用数据类型
    java运算符的优先级
    java运算符-逻辑、三元运算符
  • 原文地址:https://www.cnblogs.com/achengmu/p/9438129.html
Copyright © 2020-2023  润新知