Java MD5加密程式碼
package com.hqyj.shiro;
import java.util.HashSet; import java.util.Set;
import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired;
import com.hqyj.po.User; import com.hqyj.service.UserService;
public class MyRealm extends AuthorizingRealm{ @Autowired private UserService service; //認證方法 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // TODO Auto-generated method stub // System.out.println("realm:"+token.hashCode()); // System.out.println(token.getPrincipal());
//使用者名稱:admin,密碼為123 // if(!token.getPrincipal().equals("admin")){ // throw new UnknownAccountException(); // } // UsernamePasswordToken utoken=(UsernamePasswordToken)token; // String pwd=new String(utoken.getPassword()); // if(!(pwd.equals("123"))){ // throw new IncorrectCredentialsException(); // } UsernamePasswordToken utoken=(UsernamePasswordToken)token; String pwd=new String(utoken.getPassword()); User user=service.findByUsernameAndPwd((String)token.getPrincipal(), pwd); if(user==null){ throw new IncorrectCredentialsException(); } SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName()); return info;
} public static void main(String[] args) { // hashAlgorithmName:加密演算法 // Credentials:原始密碼 // Salt:鹽值 // hashIterations:加密次數 Object Salt="zyl"; SimpleHash simplehash= new SimpleHash("Md5", "123456", Salt, 1024); System.out.println(simplehash); //038bdaf98f2037b31f1e75b5b4c9b26e,admin //90b2b8819937e37ab28c05b94877ba12 ,zhh,123456 } //用於授權 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // TODO Auto-generated method stub Set<String> roles=new HashSet<String>(); roles.add("user"); if(principals.getPrimaryPrincipal().equals("admin")){ roles.add("admin"); } SimpleAuthorizationInfo info= new SimpleAuthorizationInfo(); for(String role:roles){ info.addRole(role); } return info; }
}