spring security 安全策略加密解密处理过程

1.现在后台生成密钥对,把得到公钥的加密系数,加密指数,传个前台登录界面,进行加密

//rsa生成密钥对,和加密解密函数。

[java]  view plain  copy
  1. public class RSAUtil  
  2. {  
  3.   private static String RSAKeyStore = "RSAKey.txt"  
  4.   
  5.   public static KeyPair generateKeyPair()  
  6.     throws Exception  
  7.   {  
  8.     try  
  9.     {  
  10.       KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",   
  11.         new BouncyCastleProvider());  
  12.       int KEY_SIZE = 1024;  
  13.       keyPairGen.initialize(1024new SecureRandom());  
  14.       KeyPair keyPair = keyPairGen.generateKeyPair();  
  15.   
  16.       System.out.println(keyPair.getPrivate().toString().length());  
  17.       System.out.println(keyPair.getPublic());  
  18.   
  19.       saveKeyPair(keyPair);  
  20.       return keyPair;  
  21.     } catch (Exception e) {  
  22.       throw new Exception(e.getMessage());  
  23.     }  
  24.   }  
  25.   
  26.   public static KeyPair getKeyPair() throws Exception {  
  27.     FileInputStream fis = new FileInputStream(Constants_core.ContextRealPath + File.separator + RSAKeyStore);  
  28.     ObjectInputStream oos = new ObjectInputStream(fis);  
  29.     KeyPair kp = (KeyPair)oos.readObject();  
  30.     oos.close();  
  31.     fis.close();  
  32.     return kp;  
  33.   }  
  34.   
  35.   public static void saveKeyPair(KeyPair kp) throws Exception  
  36.   {  
  37.     FileOutputStream fos = new FileOutputStream(Constants_core.ContextRealPath + File.separator + RSAKeyStore);  
  38.     ObjectOutputStream oos = new ObjectOutputStream(fos);  
  39.   
  40.     oos.writeObject(kp);  
  41.     oos.close();  
  42.     fos.close();  
  43.   }  
  44.   
  45.   public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent)  
  46.     throws Exception  
  47.   {  
  48.     KeyFactory keyFac = null;  
  49.     try {  
  50.       keyFac = KeyFactory.getInstance("RSA",   
  51.         new BouncyCastleProvider());  
  52.     } catch (NoSuchAlgorithmException ex) {  
  53.       throw new Exception(ex.getMessage());  
  54.     }  
  55.   
  56.     RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(  
  57.       new BigInteger(modulus), new BigInteger(publicExponent));  
  58.     try {  
  59.       return (RSAPublicKey)keyFac.generatePublic(pubKeySpec);  
  60.     } catch (InvalidKeySpecException ex) {  
  61.       throw new Exception(ex.getMessage());  
  62.     }  
  63.   }  
  64.   
  65.   public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent)  
  66.     throws Exception  
  67.   {  
  68.     KeyFactory keyFac = null;  
  69.     try {  
  70.       keyFac = KeyFactory.getInstance("RSA",   
  71.         new BouncyCastleProvider());  
  72.     } catch (NoSuchAlgorithmException ex) {  
  73.       throw new Exception(ex.getMessage());  
  74.     }  
  75.   
  76.     RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(  
  77.       new BigInteger(modulus), new BigInteger(privateExponent));  
  78.     try {  
  79.       return (RSAPrivateKey)keyFac.generatePrivate(priKeySpec);  
  80.     } catch (InvalidKeySpecException ex) {  
  81.       throw new Exception(ex.getMessage());  
  82.     }  
  83.   }  
  84.   
  85.   public static byte[] encrypt(PublicKey pk, byte[] data)  
  86.     throws Exception  
  87.   {  
  88.     try  
  89.     {  
  90.       Cipher cipher = Cipher.getInstance("RSA",   
  91.         new BouncyCastleProvider());  
  92.       cipher.init(1, pk);  
  93.       int blockSize = cipher.getBlockSize();  
  94.   
  95.       int outputSize = cipher.getOutputSize(data.length);  
  96.       int leavedSize = data.length % blockSize;  
  97.       int blocksSize = (leavedSize != 0) ? data.length / blockSize + 1 :   
  98.         data.length / blockSize;  
  99.       byte[] raw = new byte[outputSize * blocksSize];  
  100.       int i = 0;  
  101.       while (data.length - i * blockSize > 0) {  
  102.         if (data.length - i * blockSize > blockSize)  
  103.           cipher.doFinal(data, i * blockSize, blockSize, raw, i *   
  104.             outputSize);  
  105.         else {  
  106.           cipher.doFinal(data, i * blockSize, data.length - i *   
  107.             blockSize, raw, i * outputSize);  
  108.         }  
  109.   
  110.         ++i;  
  111.       }  
  112.       return raw;  
  113.     } catch (Exception e) {  
  114.       throw new Exception(e.getMessage());  
  115.     }  
  116.   }  
  117.   
  118.   public static byte[] decrypt(PrivateKey pk, byte[] raw)  
  119.     throws Exception  
  120.   {  
  121.     try  
  122.     {  
  123.       Cipher cipher = Cipher.getInstance("RSA",   
  124.         new BouncyCastleProvider());  
  125.       cipher.init(2, pk);  
  126.       int blockSize = cipher.getBlockSize();  
  127.       ByteArrayOutputStream bout = new ByteArrayOutputStream(64);  
  128.       int j = 0;  
  129.   
  130.       while (raw.length - j * blockSize > 0) {  
  131.         bout.write(cipher.doFinal(raw, j * blockSize, blockSize));  
  132.         ++j;  
  133.       }  
  134.       return bout.toByteArray();  
  135.     } catch (Exception e) {  
  136.       throw new Exception(e.getMessage());  
  137.     }  
  138.   }  
  139.   
  140.   public static String decrypt(PrivateKey pk, String str_en)  
  141.     throws Exception  
  142.   {  
  143.     String str_mw = "";  
  144.     byte[] en_result = new BigInteger(str_en, 16).toByteArray();  
  145.     byte[] de_result = decrypt(getKeyPair().getPrivate(), en_result);  
  146.     StringBuffer sb = new StringBuffer();  
  147.     sb.append(new String(de_result));  
  148.     str_mw = sb.reverse().toString();  
  149.     str_mw = URLDecoder.decode(str_mw, "UTF-8");  
  150.     return str_mw;  
  151.   }  
  152.   
  153.   public static void main(String[] args)  
  154.     throws Exception  
  155.   {  
  156.     Constants_core.ContextRealPath = "D:/EPS/ygpt/WebRoot";  
  157.     String test = "hello world";  
  158.     byte[] en_test = encrypt(getKeyPair().getPublic(), test.getBytes());  
  159.     String stren = Base64.encode(en_test);  
  160.     byte[] de_test = decrypt(getKeyPair().getPrivate(), Base64.decode(stren));  
  161.     System.out.println(new String(de_test));  
  162.   }  
  163. }  
//前台js加密

[java]  view plain  copy
  1. var j_password = document.getElementById("j_password_show").value;  
  2.       document.getElementById("j_password").value = encryptedString(key, encodeURIComponent(j_password));  
  3.        
  4.        LOGIN_FORM.submit();  

2.点击登录时,密码被用rsa加密后发到spring security的 DaoAuthenticationProvider 进行密码校验处理,

在密码发到后台后,先用在第一步时产生的私钥进行解密,解密后再用spring security 提供的 passwordEncoder类的

this.passwordEncoder.isPasswordValid()方法来进行,密码校验。


[java]  view plain  copy
  1. public DaoAuthenticationProvider()  
  2.   {  
  3.     setPasswordEncoder(new PlaintextPasswordEncoder());  
  4.   }  
  5.   
  6.   protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication)  
  7.     throws AuthenticationException  
  8.   {  
  9.     Object salt = null;  
  10.   
  11.     if (this.saltSource != null) {  
  12.       salt = this.saltSource.getSalt(userDetails);  
  13.     }  
  14.   
  15.     if (authentication.getCredentials() == null) {  
  16.       this.logger.debug("Authentication failed: no credentials provided");  
  17.   
  18.       throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials""Bad credentials"), userDetails);  
  19.     }  
  20.     //rsa私钥解密  
  21.     try {  
  22.                 presentedPassword = RSAUtil.decrypt(RSAUtil.getKeyPair().getPrivate(),presentedPassword);  
  23.             } catch (Exception e) {  
  24.                 this.logger.error(e, e.fillInStackTrace());  
  25.             }  
  26.   
  27.     String presentedPassword = authentication.getCredentials().toString();  
  28.     //校验密码  
  29.     if (!this.passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {  
  30.       this.logger.debug("Authentication failed: password does not match stored value");  
  31.   
  32.       throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials""Bad credentials"), userDetails);  
  33.     }  
  34.   }  
  35.   
  36.   protected void doAfterPropertiesSet() throws Exception  
  37.   {  
  38.     Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");  
  39.   }  
  40.   
  41.   protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException  
  42.   {  
  43.     UserDetails loadedUser;  
  44.     try  
  45.     {  
  46.       loadedUser = getUserDetailsService().loadUserByUsername(username);  
  47.     } catch (UsernameNotFoundException notFound) {  
  48.       if (authentication.getCredentials() != null) {  
  49.         String presentedPassword = authentication.getCredentials().toString();  
  50.         this.passwordEncoder.isPasswordValid(this.userNotFoundEncodedPassword, presentedPassword, null);  
  51.       }  
  52.       throw notFound;  
  53.     } catch (Exception repositoryProblem) {  
  54.       throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);  
  55.     }  
  56.   
  57.     if (loadedUser == null) {  
  58.       throw new AuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");  
  59.     }  
  60.   
  61.     return loadedUser;  
  62.   }  
  63.   
  64.   public void setPasswordEncoder(Object passwordEncoder)  
  65.   {  
  66.     Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");  
  67.   
  68.     if (passwordEncoder instanceof org.springframework.security.authentication.encoding.PasswordEncoder) {  
  69.       setPasswordEncoder((org.springframework.security.authentication.encoding.PasswordEncoder)passwordEncoder);  
  70.       return;  
  71.     }  
  72.   
  73.     if (passwordEncoder instanceof org.springframework.security.crypto.password.PasswordEncoder) {  
  74.       org.springframework.security.crypto.password.PasswordEncoder delegate = (org.springframework.security.crypto.password.PasswordEncoder)passwordEncoder;  
  75.   
  76.       setPasswordEncoder(new org.springframework.security.authentication.encoding.PasswordEncoder(delegate) {  
  77.         public String encodePassword(String rawPass, Object salt) {  
  78.           checkSalt(salt);  
  79.           return this.val$delegate.encode(rawPass);  
  80.         }  
  81.   
  82.         public boolean isPasswordValid(String encPass, String rawPass, Object salt) {  
  83.           checkSalt(salt);  
  84.           return this.val$delegate.matches(rawPass, encPass);  
  85.         }  
  86.   
  87.         private void checkSalt(Object salt) {  
  88.           Assert.isNull(salt, "Salt value must be null when used with crypto module PasswordEncoder");  
  89.         }  
  90.       });  
  91.       return;  
  92.     }  
  93.   
  94.     throw new IllegalArgumentException("passwordEncoder must be a PasswordEncoder instance");  
  95.   }  
  96.   
  97.   private void setPasswordEncoder(org.springframework.security.authentication.encoding.PasswordEncoder passwordEncoder) {  
  98.     Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");  
  99.   
  100.     this.userNotFoundEncodedPassword = passwordEncoder.encodePassword("userNotFoundPassword"null);  
  101.     this.passwordEncoder = passwordEncoder;  
  102.   }  
  103.   
  104.   protected org.springframework.security.authentication.encoding.PasswordEncoder getPasswordEncoder() {  
  105.     return this.passwordEncoder;  
  106.   }  
  107.   
  108.   public void setSaltSource(SaltSource saltSource)  
  109.   {  
  110.     this.saltSource = saltSource;  
  111.   }  
  112.   
  113.   protected SaltSource getSaltSource() {  
  114.     return this.saltSource;  
  115.   }  
  116.   
  117.   public void setUserDetailsService(UserDetailsService userDetailsService) {  
  118.     this.userDetailsService = userDetailsService;  
  119.   }  
  120.   
  121.   protected UserDetailsService getUserDetailsService() {  
  122.     return this.userDetailsService;  
  123.   }  
  124. }  

3.为什么这么做呢,因为,后台数据库存储的密码都是经过不可逆算法加密过的,用这个方法,对3第三部解密后的密码在进行加密处理,最后和数据存储的加密密码进行比较,返回true则密码通过验证。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值