美文网首页
微信小程序加密数据解密-java

微信小程序加密数据解密-java

作者: 小蓝田 | 来源:发表于2019-07-17 14:32 被阅读0次

    通过 java 实现微信小程序用户加密数据的解密

    • 环境:
      window 或 linux
      jdk1.7
    • 所需依赖:
    <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
        <dependency>
          <groupId>commons-codec</groupId>
          <artifactId>commons-codec</artifactId>
          <version>1.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
        <dependency>
          <groupId>org.bouncycastle</groupId>
          <artifactId>bcprov-jdk15on</artifactId>
          <version>1.57</version>
        </dependency>
    
    • 代码实现:
    package com.test.utils;
    
    import org.apache.commons.codec.binary.Base64;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    
    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.Security;
    import java.security.spec.AlgorithmParameterSpec;
    
    public class DecryptionUtils {
    
        public static String decode(String sessionKey,String encryptedData,String iv)
                throws Exception{
            byte[] encrypData = Base64.decodeBase64(encryptedData);
            byte[] ivData = Base64.decodeBase64(iv);
            byte[] sessionKeyB = Base64.decodeBase64(sessionKey);
            Security.addProvider(new BouncyCastleProvider());
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec keySpec = new SecretKeySpec(sessionKeyB, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] doFinal = cipher.doFinal(encrypData);
            return new String(doFinal);
        }
    }
    
    

    注意

    如果解密报错 javax.crypto.BadPaddingException: pad block corrupted 极有可能是因为sessionKeyencryptedDataiv不匹配

    相关文章

      网友评论

          本文标题:微信小程序加密数据解密-java

          本文链接:https://www.haomeiwen.com/subject/uxmqlctx.html