zoukankan      html  css  js  c++  java
  • Java AES、RSA 加密解密

     

     颜色相同的代表一对公私钥,本图涉及到四套证书,浅绿浅粉块的是自己的两套证书,浅黄浅蓝第三方证书。

    RSA 加密

    String data="xml格式或json格式的业务报文数据,对整个报文加解密";
    String encryptKey=AESUtil.getRandomAESKey();
    byte[] encryptBusinessDataByte=AESUtil.encrypt(data, encryptKey);
    String encryptBusiness = new String(CBBase64.encode(encryptBusinessDataByte),"UTF-8");        
    
    //公钥文件路径
    String publicKeyFile="/usr/sercert/publicKeyCert.crt";
    byte[] base64EncodedPublickey = FileUtil.read4file(publicKeyFile);   //或者:publicKeyString.getBytes("UTF-8");
    
    X509Certificate signerCertificate = CryptUtil.generateX509Certificate(com.lsy.baselib.crypto.util.Base64.decode(base64EncodedPublickey));
    PublicKey signpublicKey = signerCertificate.getPublicKey();
                
    byte[] encryptKeyByte=CBRSA.encrypt((RSAKey) signpublicKey, encryptKey.getBytes(""UTF-8""));
    String encryptKeyString=new String(CBBase64.encode(encryptKeyByte),"UTF-8");
    
    //加密后的报文,放入encryptBody
    encryptBusiness=encryptBusiness+"@@"+encryptKeyString;
    View Code

    RSA 解密

    String decryptedBusinessData=null;
    String[] encryptBusinessDataArr=encryptBusiness.split("@@");
    String encryptKey=encryptBusinessDataArr[1];
    try {
            //私钥文件路径
            String keyfile = “/usr/cert/privateKeyCert.key”;
            byte[] base64EncodedPrivatekey = FileUtil.read4file(keyfile);
            //私钥密码文件路径
            String pwdfile = "/usr/cert/privateKeyCert.pwd";
            byte[] base64EncodedPrivatekeyPass = FileUtil.read4file(pwdfile);
            char[] keyPassword = new String(base64EncodedPrivatekeyPass, "UTF-8").toCharArray();
            RSAPrivateKey privateKey =  (RSAPrivateKey) CryptUtil.decryptPrivateKey(Base64.decode(base64EncodedPrivatekey), keyPassword);
            byte[] keyByte=CBRSA.decrypt(privateKey, CBBase64.decode(encryptKey.getBytes(“UTF-8”)));
            String encryptKeystr=new String(keyByte,"UTF-8");
    
            byte[] decryptedBusinessDataBytes = AESUtil.decrypt(CBBase64.decode(encryptBusinessDataArr[0].getBytes(“UTF-8”)), encryptKeystr);
            //得到解密后的明文字符串
            decryptedBusinessData = new String(decryptedBusinessDataBytes, "UTF-8");
    } catch (Exception e) {
           logger.error(e.getStackTrace(), e);
    }
    View Code

    CBRSA 算法工具类

    import java.io.ByteArrayOutputStream;
    import java.security.Key;
    import java.security.interfaces.RSAKey;
    
    import javax.crypto.Cipher;
    
    public class CBRSA {
     public static byte[] encrypt(RSAKey key, byte[] data) throws Exception {
      try {
       Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding", "BC");
       cipher.init(1, (Key) key);
       int step = key.getModulus().bitLength() / 8;
       int n = data.length / step;
       if (n > 0) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        for (int i = 0; i < n; i++) {
         baos.write(cipher.doFinal(data, i * step, step));
        }
        if ((n = data.length % step) != 0) {
         baos.write(cipher.doFinal(data, data.length - n, n));
        }
        return baos.toByteArray();
       }
       return cipher.doFinal(data);
      } catch (Exception e) {
       throw new Exception("MPCM033");
      }
     }
    
     public static byte[] decrypt(RSAKey key, byte[] raw) throws Exception {
      try {
       Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding", "BC");
       cipher.init(2, (Key) key);
       int step = key.getModulus().bitLength() / 8;
       int n = raw.length / step;
       if (n > 0) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        for (int i = 0; i < n; i++) {
         baos.write(cipher.doFinal(raw, i * step, step));
        }
        return baos.toByteArray();
       }
       return cipher.doFinal(raw);
      } catch (Exception e) {
       throw new Exception("MPCM033");
      }
     }
    }
    View Code

    AES 算法工具类

    import java.security.InvalidAlgorithmParameterException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.util.Random;
    
    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    
    public class AESUtil1 {
     private static int KeySizeAES128 = 16;
    
     private static Cipher getCipher(int mode, String key) {
      // mode =Cipher.DECRYPT_MODE or Cipher.ENCRYPT_MODE
      Cipher mCipher;
      byte[] keyPtr = new byte[KeySizeAES128];
      IvParameterSpec ivParam = new IvParameterSpec(keyPtr);
      byte[] passPtr = key.getBytes();
      try {
       mCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
       for (int i = 0; i < KeySizeAES128; i++) {
        if (i < passPtr.length)
         keyPtr[i] = passPtr[i];
        else
         keyPtr[i] = 0;
       }
       SecretKeySpec keySpec = new SecretKeySpec(keyPtr, "AES");
       mCipher.init(mode, keySpec, ivParam);
       return mCipher;
      } catch (InvalidKeyException e) {
       e.printStackTrace();
      } catch (NoSuchAlgorithmException e) {
       e.printStackTrace();
      } catch (NoSuchPaddingException e) {
       e.printStackTrace();
      } catch (InvalidAlgorithmParameterException e) {
       e.printStackTrace();
      }
      return null;
     }
    
     public static byte[] encrypt(String content, String password) {
      try {
       Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, password);// 创建密码器
       byte[] result = cipher.doFinal(content.getBytes("UTF-8"));// 加密
       return result;
      } catch (Exception e) {
       e.printStackTrace();
      }
      return null;
     }
    
     public static byte[] decrypt(byte[] content, String password) {
      try {
       Cipher cipher = getCipher(Cipher.DECRYPT_MODE, password);// 创建密码器
       byte[] result = cipher.doFinal(content);
       return result; // 明文
      } catch (Exception e) {
       e.printStackTrace();
      }
      return null;
     }
    
     public static String getRandomAESKey() {
      int $aes_ken_len = 16;
      String aes_key_str = "";
      char[] e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
        .toCharArray();
      int index = 0;
      Random r = new Random();
      for (int i = 0; i < $aes_ken_len; i++) {
       index = r.nextInt(64);
       aes_key_str += e[index];
      }
      return aes_key_str;
     }
    }
    View Code
  • 相关阅读:
    无线鼠标换电池了
    Jython Interactive Servlet Console YOU WILL NEVER KNOW IT EXECLLENT!!! GOOD
    Accessing Jython from Java Without Using jythonc
    jython podcast cool isnt't it?
    Python里pycurl使用记录
    Creating an Interactive JRuby Console for the Eclipse Environment
    微软为AJAX和jQuery类库提供CDN服务
    Download A File Using Cygwin and cURL
    What is JMRI?这个是做什么用的,我真没看懂但看着又很强大
    用curl 发送指定的大cookie的http/https request
  • 原文地址:https://www.cnblogs.com/BabyRui/p/12166979.html
Copyright © 2011-2022 走看看