第五章 编码/加密

来源:互联网 发布:js中createelement 编辑:程序博客网 时间:2024/05/08 00:23

一、编码 / 解码

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

/* * base64编码/解码 */public void Base64Demo(){String str = "hello";String base64Encoded = Base64.encodeToString(str.getBytes());String str2 = Base64.decodeToString(base64Encoded);System.out.println(base64Encoded);System.out.println(str2);}

通过如上方式可以进行base64 编码/解码操作,更多API请参考其Javadoc。

/* * 16进制编码/解码 */public void Demo16(){String str = "hello";String base64Encoded = Hex.encodeToString(str.getBytes());String str2 = new String(Hex.decode(base64Encoded.getBytes()));System.out.println(base64Encoded);System.out.println(str2);}
通过如上方式可以进行16进制字符串编码/解码操作,更多API请参考其Javadoc。

还有一个可能经常用到的类CodecSupport,提供了toBytes(str, "utf-8") / toString(bytes,"utf-8")用于在byte 数组/String 之间转换。

二、散列算法

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

1. MD5散列算法

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

public void Demo1(){String str = "hello";//待加密字符串String salt = "123";//盐String md5 = new Md5Hash(str, salt).toString();//还可以转换为toBase64()、toHex()System.out.println(md5);}

2. SHA256散列算法

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

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

3. Shiro提供的通用散列支持

通过调用SimpleHash时指定散列算法,其内部使用了Java 的MessageDigest实现。

public void Demo3(){String str = "hello";String salt = "123";//内部使用MessageDigestString simpleHash = new SimpleHash("SHA-1",str,salt).toString();System.out.println(simpleHash);}

4. Shiro提供的HashService

为了方便使用,Shiro 提供了HashService,默认提供了DefaultHashService实现。

public void HashServiceDemo(){DefaultHashService hashService = new DefaultHashService(); //默认算法SHA-512hashService.setHashAlgorithmName("SHA-512");hashService.setPrivateSalt(new SimpleByteSource("123")); //私盐,默认无hashService.setGeneratePublicSalt(true); //是否生成公盐,默认falsehashService.setRandomNumberGenerator(new SecureRandomNumberGenerator()); //用于生成公盐,默认就这个hashService.setHashIterations(1); //生成Hash值的迭代次数HashRequest request = new HashRequest.Builder().setAlgorithmName("MD5").setSource(ByteSource.Util.bytes("hello")).setSalt(ByteSource.Util.bytes("123")).setIterations(2).build();String hex = hashService.computeHash(request).toHex();System.out.println(hex);}
1)首先创建一个DefaultHashService,默认使用SHA-512 算法;

2)可以通过hashAlgorithmName属性修改算法;

3)可以通过privateSalt设置一个私盐,其在散列时自动与用户传入的公盐混合产生一个新盐;

4)可以通过generatePublicSalt属性在用户没有传入公盐的情况下是否生成公盐;

5)可以设置randomNumberGenerator用于生成公盐;

6)可以设置hashIterations属性来修改默认加密迭代次数;

7)需要构建一个HashRequest,传入算法、数据、公盐、迭代次数。

5. SecureRandomNumberGenerator用于生成一个随机数:

public void RandomNumber(){SecureRandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();randomNumberGenerator.setSeed("123".getBytes());String hex = randomNumberGenerator.nextBytes().toHex();System.out.println(hex);}
三、加密 / 解密

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

1. AES算法实现

public void JiaJieMi(){AesCipherService aesCipherService = new AesCipherService();aesCipherService.setKeySize(128);//设置key长度//生成keyKey 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());System.out.println(encrptText);System.out.println(text2);}
四、PasswordService / CredentialsMatcher

Shiro 提供了PasswordService及CredentialsMatcher用于提供加密密码及验证密码服务。

public interface PasswordService {//输入明文密码得到密文密码String encryptPassword(Object plaintextPassword) throws IllegalArgumentException;}
public interface CredentialsMatcher {//匹配用户输入的token 的凭证(未加密)与系统提供的凭证(已加密)boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info);}

Shiro 默认提供了PasswordService 实现DefaultPasswordService;CredentialsMatcher 实现PasswordMatcher及HashedCredentialsMatcher(更强大)

1. DefaultPasswordService配合PasswordMatcher实现简单的密码加密与验证服务

1)定义Realm

public class MyRealm extends AuthorizingRealm{private PasswordService passwordService;public void setPasswordService(PasswordService passwordService) {this.passwordService = passwordService;}protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {return null;}protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("wu",passwordService.encryptPassword("123"),getName());return authenticationInfo;}}
为了方便,直接注入一个passwordService 来加密密码,实际使用时需要在Service 层使用passwordService加密密码并存到数据库。

2)ini配置(shiro-passwordservice.ini)

[main]passwordService=org.apache.shiro.authc.credential.DefaultPasswordServicehashService=org.apache.shiro.crypto.hash.DefaultHashServicepasswordService.hashService=$hashServicehashFormat=org.apache.shiro.crypto.hash.format.Shiro1CryptFormatpasswordService.hashFormat=$hashFormathashFormatFactory=org.apache.shiro.crypto.hash.format.DefaultHashFormatFactorypasswordService.hashFormatFactory=$hashFormatFactorypasswordMatcher=org.apache.shiro.authc.credential.PasswordMatcherpasswordMatcher.passwordService=$passwordServicemyRealm=chapter5.MyRealmmyRealm.passwordService=$passwordServicemyRealm.credentialsMatcher=$passwordMatchersecurityManager.realms=$myRealm

(1)passwordService使用DefaultPasswordService,如果有必要也可以自定义;

(2)hashService 定义散列密码使用的HashService,默认使用DefaultHashService(默认SHA-256 算法);

(3)hashFormat用于对散列出的值进行格式化,默认使用Shiro1CryptFormat,另外提供了Base64Format 和HexFormat,对于有salt 的密码请自定义实现ParsableHashFormat 然后把salt格式化到散列值中;

(4)hashFormatFactory用于根据散列值得到散列的密码和salt;因为如果使用如SHA 算法,那么会生成一个salt,此salt需要保存到散列后的值中以便之后与传入的密码比较时使用;默认使用DefaultHashFormatFactory;

(5)passwordMatcher使用PasswordMatcher,其是一个CredentialsMatcher实现;

(6)将credentialsMatcher赋值给myRealm,myRealm间接继承了AuthenticatingRealm,其在调用getAuthenticationInfo 方法获取到AuthenticationInfo 信息后, 会使用credentialsMatcher 来验证凭据是否匹配,如果不匹配将抛出IncorrectCredentialsException异常。

注:JDBC验证版本配置

[main]myRealm=chapter5.MyRealmpasswordService=org.apache.shiro.authc.credential.DefaultPasswordServicehashService=org.apache.shiro.crypto.hash.DefaultHashServicepasswordService.hashService=$hashServicehashFormat=org.apache.shiro.crypto.hash.format.Shiro1CryptFormatpasswordService.hashFormat=$hashFormathashFormatFactory=org.apache.shiro.crypto.hash.format.DefaultHashFormatFactorypasswordService.hashFormatFactory=$hashFormatFactorypasswordMatcher=org.apache.shiro.authc.credential.PasswordMatcherpasswordMatcher.passwordService=$passwordServicedataSource=com.mchange.v2.c3p0.ComboPooledDataSourcedataSource.driverClass=com.mysql.jdbc.DriverdataSource.jdbcUrl=jdbc:mysql://localhost:3306/shirodataSource.user=rootdataSource.password=123456jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealmjdbcRealm.dataSource=$dataSourcejdbcRealm.permissionsLookupEnabled=truejdbcRealm.credentialsMatcher=$passwordMatchersecurityManager.realms=$jdbcRealm

3)测试

public class PasswordTest {@Testpublic void testPasswordServiceWithMyReal(){login("classpath:chapter5/shiro-passwordservice.ini","wu","123");}public void login(String configFile,String username,String password){//1. 获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManagerFactory<SecurityManager> factory = new IniSecurityManagerFactory(configFile);//2. 得到SecurityManager实例,并绑定给SecurityUtilsSecurityManager securityManager = factory.getInstance();SecurityUtils.setSecurityManager(securityManager);//3. 得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)Subject subject = SecurityUtils.getSubject();UsernamePasswordToken token = new UsernamePasswordToken(username,password);subject.login(token);}}

2. HashedCredentialsMatcher实现密码验证服务

Shiro 提供了CredentialsMatcher 的散列实现HashedCredentialsMatcher,和之前的PasswordMatcher不同的是,它只用于密码验证,且可以提供自己的盐,而不是随机生成盐,且生成密码散列值的算法需要自己写,因为能提供自己的盐。

1)生成密码散列值

此处我们使用MD5算法,“密码+盐(用户名+随机数)”的方式生成散列值:

public void getSlz(){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);}
如果要写用户模块,需要在新增用户/重置密码时使用如上算法保存密码,将生成的密码及salt2存入数据库(因为我们的散列算法是:md5(md5(密码+username+salt2)))。

2)生成Realm(chapter5 / MyRealm2.java)

public class MyRealm2 extends AuthorizingRealm{protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {return null;}protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {String username = "liu";//用户名及salt1String password = "be320beca57748ab9632c4121ccac0db"; //加密后的密码String salt2 = "0072273a5d87322163795118fdd7c45e";SimpleAuthenticationInfo ai = new SimpleAuthenticationInfo(username,password,getName());ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2));//盐是用户名+随机数return ai;}}

此 处就是把步骤1 中生成的相应数据组装为SimpleAuthenticationInfo , 通过SimpleAuthenticationInfo 的credentialsSalt设置盐,HashedCredentialsMatcher会自动识别这个盐。

3)ini配置(shiro-hashedCredentialsMatcher.ini)

[main]credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatchercredentialsMatcher.hashAlgorithmName=md5credentialsMatcher.hashIterations=2credentialsMatcher.storedCredentialsHexEncoded=truemyRealm=chapter5.MyRealm2myRealm.credentialsMatcher=$credentialsMatchersecurityManager.realms=$myRealm
(1)通过credentialsMatcher.hashAlgorithmName=md5 指定散列算法为md5,需要和生成密码时的一样;

(2)credentialsMatcher.hashIterations=2,散列迭代次数,需要和生成密码时的意义;

(3)credentialsMatcher.storedCredentialsHexEncoded=true表示是否存储散列后的密码为16 进制,需要和生成密码时的一样,默认是base64;

此处最需要注意的就是HashedCredentialsMatcher的算法需要和生成密码时的算法一样。另外HashedCredentialsMatcher 会自动根据AuthenticationInfo 的类型是否是SaltedAuthenticationInfo来获取credentialsSalt盐。

4)测试

public void testHashedCredentialsMatcherWithMyRealm2(){//使用testGeneratePassword生成散列密码login("classpath:chapter5/shiro-hashedCredentialsMatcher.ini","liu","123");}

注:JDBC验证版本配置

(1)shiro-jdbc-hashedCredentialsMatcher.ini

[main]credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatchercredentialsMatcher.hashAlgorithmName=md5credentialsMatcher.hashIterations=2credentialsMatcher.storedCredentialsHexEncoded=truedataSource=com.mchange.v2.c3p0.ComboPooledDataSourcedataSource.driverClass=com.mysql.jdbc.DriverdataSource.jdbcUrl=jdbc:mysql://localhost:3306/shirodataSource.user=rootdataSource.password=123456jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealmjdbcRealm.dataSource=$dataSourcejdbcRealm.permissionsLookupEnabled=truejdbcRealm.saltStyle=COLUMNjdbcRealm.authenticationQuery=select password,concat(username,password_salt) from users where username = ?jdbcRealm.credentialsMatcher=$credentialsMatchersecurityManager.realms=$jdbcRealm

saltStyle 表示使用密码+盐的机制,authenticationQuery第一列是密码,第二列是盐;

通过authenticationQuery指定密码及盐查询SQL;

此处还要注意Shiro 默认使用了apache commons BeanUtils,默认是不进行Enum类型转型的, 此时需要自己注册一个Enum 转换器“BeanUtilsBean.getInstance().getConvertUtils().register(new EnumConverter(),JdbcRealm.SaltStyle.class); ” 如下:

(2)测试

@Testpublic void testHashedCredentialsMatcherWithJdbcRealm(){BeanUtilsBean.getInstance().getConvertUtils().register(new EnumConverter(), JdbcRealm.SaltStyle.class);//使用testGeneratePassword生成散列密码login("classpath:chapter5/shiro-hashedCredentialsMatcher.ini","liu","123");}private class EnumConverter extends AbstractConverter{@Overrideprotected String convertToString(final Object value)throws Throwable {return ((Enum) value).name();}@Overrideprotected Object convertToType(final Class type, final Object value)throws Throwable {return Enum.valueOf(type, value.toString());}@Overrideprotected Class getDefaultType() {return null;}}