java 加密工具类(MD5、RSA、AES等加密方式)

java

1.加密工具类encryption

MD5加密

[java] view plain copy print?

  1. import org.apache.commons.codec.digest.DigestUtils;  
  2.   
  3. /** 
  4.  * MD5加密组件 
  5.  *  
  6.  * @author wbw 
  7.  * @version 1.0 
  8.  * @since 1.0 
  9.  */  
  10. public abstract class MD5Util {  
  11.   
  12.     /** 
  13.      * MD5加密 
  14.      *  
  15.      * @param data 
  16.      *            待加密数据 
  17.      * @return byte[] 消息摘要 
  18.      *  
  19.      * @throws Exception 
  20.      */  
  21.     public static byte[] encodeMD5(String data) throws Exception {  
  22.   
  23.         // 执行消息摘要  
  24.         return DigestUtils.md5(data);  
  25.     }  
  26.   
  27.     /** 
  28.      * MD5加密 
  29.      *  
  30.      * @param data 
  31.      *            待加密数据 
  32.      * @return byte[] 消息摘要 
  33.      *  
  34.      * @throws Exception 
  35.      */  
  36.     public static String encodeMD5Hex(String data) {  
  37.         // 执行消息摘要  
  38.         return DigestUtils.md5Hex(data);  
  39.     }  
  40. }  

import org.apache.commons.codec.digest.DigestUtils;

/**

  • MD5加密组件

  • @author wbw

  • @version 1.0

  • @since 1.0

    */

    public abstract class MD5Util {

    /**

    • MD5加密

    • @param data

    •        待加密数据

    • @return byte[] 消息摘要

    • @throws Exception

      */

      public static byte[] encodeMD5(String data) throws Exception {

      // 执行消息摘要

      return DigestUtils.md5(data);

      }

    /**

    • MD5加密
    • @param data
    •        待加密数据

    • @return byte[] 消息摘要
    • @throws Exception

      */

      public static String encodeMD5Hex(String data) {

      // 执行消息摘要

      return DigestUtils.md5Hex(data);

      }

      }

AES加密:

[java] view plain copy print?

  1. import javax.crypto.Cipher;  
  2. import javax.crypto.spec.SecretKeySpec;  
  3.   
  4. public class AESUtil {  
  5.   
  6.     private static final String KEY_AES = "AES";  
  7.   
  8.     public static String encrypt(String src, String key) throws Exception {  
  9.         if (key == null || key.length() != 16) {  
  10.             throw new Exception("key不满足条件");  
  11.         }   
  12.         byte[] raw = key.getBytes();  
  13.         SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);  
  14.         Cipher cipher = Cipher.getInstance(KEY_AES);  
  15.         cipher.init(Cipher.ENCRYPT_MODE, skeySpec);  
  16.         byte[] encrypted = cipher.doFinal(src.getBytes());  
  17.         return byte2hex(encrypted);  
  18.     }  
  19.   
  20.     public static String decrypt(String src, String key) throws Exception {  
  21.         if (key == null || key.length() != 16) {  
  22.             throw new Exception("key不满足条件");  
  23.         }  
  24.         byte[] raw = key.getBytes();  
  25.         SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);  
  26.         Cipher cipher = Cipher.getInstance(KEY_AES);  
  27.         cipher.init(Cipher.DECRYPT_MODE, skeySpec);  
  28.         byte[] encrypted1 = hex2byte(src);  
  29.         byte[] original = cipher.doFinal(encrypted1);  
  30.         String originalString = new String(original);  
  31.         return originalString;  
  32.     }  
  33.   
  34.     public static byte[] hex2byte(String strhex) {  
  35.         if (strhex == null) {  
  36.             return null;  
  37.         }  
  38.         int l = strhex.length();  
  39.         if (l % 2 == 1) {  
  40.             return null;  
  41.         }  
  42.         byte[] b = new byte[l / 2];  
  43.         for (int i = 0; i != l / 2; i++) {  
  44.             b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),  
  45.                     16);  
  46.         }  
  47.         return b;  
  48.     }  
  49.   
  50.     public static String byte2hex(byte[] b) {  
  51.         String hs = "";  
  52.         String stmp = "";  
  53.         for (int n = 0; n < b.length; n++) {  
  54.             stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));  
  55.             if (stmp.length() == 1) {  
  56.                 hs = hs + "0" + stmp;  
  57.             } else {  
  58.                 hs = hs + stmp;  
  59.             }  
  60.         }  
  61.         return hs.toUpperCase();  
  62.     }  
  63.   
  64. }  

import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

private static final String KEY_AES = "AES";

public static String encrypt(String src, String key) throws Exception {

if (key == null || key.length() != 16) {

throw new Exception("key不满足条件");

}

byte[] raw = key.getBytes();

SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);

Cipher cipher = Cipher.getInstance(KEY_AES);

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

byte[] encrypted = cipher.doFinal(src.getBytes());

return byte2hex(encrypted);

}

public static String decrypt(String src, String key) throws Exception {

if (key == null || key.length() != 16) {

throw new Exception("key不满足条件");

}

byte[] raw = key.getBytes();

SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);

Cipher cipher = Cipher.getInstance(KEY_AES);

cipher.init(Cipher.DECRYPT_MODE, skeySpec);

byte[] encrypted1 = hex2byte(src);

byte[] original = cipher.doFinal(encrypted1);

String originalString = new String(original);

return originalString;

}

public static byte[] hex2byte(String strhex) {

if (strhex == null) {

return null;

}

int l = strhex.length();

if (l % 2 == 1) {

return null;

}

byte[] b = new byte[l / 2];

for (int i = 0; i != l / 2; i++) {

b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),

16);

}

return b;

}

public static String byte2hex(byte[] b) {

String hs = "";

String stmp = "";

for (int n = 0; n &lt; b.length; n++) {

stmp = (java.lang.Integer.toHexString(b[n] &amp; 0XFF));

if (stmp.length() == 1) {

hs = hs + "0" + stmp;

} else {

hs = hs + stmp;

}

}

return hs.toUpperCase();

}

}

Base64加密:

[java] view plain copy print?

  1. import org.apache.commons.codec.binary.Base64;  
  2.   
  3. /** 
  4.  * Base64组件 
  5.  *  
  6.  * @author wbw 
  7.  * @version 1.0 
  8.  * @since 1.0 
  9.  */  
  10. public abstract class Base64Util {  
  11.   
  12.     /** 
  13.      * 字符编码 
  14.      */  
  15.     public final static String ENCODING = "UTF-8";  
  16.   
  17.     /** 
  18.      * Base64编码 
  19.      *  
  20.      * @param data 待编码数据 
  21.      * @return String 编码数据 
  22.      * @throws Exception 
  23.      */  
  24.     public static String encode(String data) throws Exception {  
  25.   
  26.         // 执行编码  
  27.         byte[] b = Base64.encodeBase64(data.getBytes(ENCODING));  
  28.   
  29.         return new String(b, ENCODING);  
  30.     }  
  31.   
  32.     /** 
  33.      * Base64安全编码<br> 
  34.      * 遵循RFC 2045实现 
  35.      *  
  36.      * @param data 
  37.      *            待编码数据 
  38.      * @return String 编码数据 
  39.      *  
  40.      * @throws Exception 
  41.      */  
  42.     public static String encodeSafe(String data) throws Exception {  
  43.   
  44.         // 执行编码  
  45.         byte[] b = Base64.encodeBase64(data.getBytes(ENCODING), true);  
  46.   
  47.         return new String(b, ENCODING);  
  48.     }  
  49.   
  50.     /** 
  51.      * Base64解码 
  52.      *  
  53.      * @param data 待解码数据 
  54.      * @return String 解码数据 
  55.      * @throws Exception 
  56.      */  
  57.     public static String decode(String data) throws Exception {  
  58.   
  59.         // 执行解码  
  60.         byte[] b = Base64.decodeBase64(data.getBytes(ENCODING));  
  61.   
  62.         return new String(b, ENCODING);  
  63.     }  
  64.   
  65. }  

import org.apache.commons.codec.binary.Base64;

/**

  • Base64组件

  • @author wbw

  • @version 1.0

  • @since 1.0

    */

    public abstract class Base64Util {

    /**

    • 字符编码

      */

      public final static String ENCODING = "UTF-8";

    /**

    • Base64编码

    • @param data 待编码数据

    • @return String 编码数据

    • @throws Exception

      */

      public static String encode(String data) throws Exception {

      // 执行编码

      byte[] b = Base64.encodeBase64(data.getBytes(ENCODING));

      return new String(b, ENCODING);

      }

    /**

    • Base64安全编码<br>

    • 遵循RFC 2045实现

    • @param data

    •        待编码数据

    • @return String 编码数据

    • @throws Exception

      */

      public static String encodeSafe(String data) throws Exception {

      // 执行编码

      byte[] b = Base64.encodeBase64(data.getBytes(ENCODING), true);

      return new String(b, ENCODING);

      }

    /**

    • Base64解码

    • @param data 待解码数据

    • @return String 解码数据

    • @throws Exception

      */

      public static String decode(String data) throws Exception {

      // 执行解码

      byte[] b = Base64.decodeBase64(data.getBytes(ENCODING));

      return new String(b, ENCODING);

      }

}

DES加密:

[java] view plain copy print?

  1. import java.security.Key;  
  2. import java.security.SecureRandom;  
  3. import java.security.Security;  
  4.   
  5. import javax.crypto.Cipher;  
  6. import javax.crypto.KeyGenerator;  
  7. import javax.crypto.SecretKey;  
  8. import javax.crypto.SecretKeyFactory;  
  9. import javax.crypto.spec.DESKeySpec;  
  10.   
  11. import org.apache.commons.codec.binary.Base64;  
  12. import org.bouncycastle.jce.provider.BouncyCastleProvider;  
  13.   
  14. /** 
  15.  * DES安全编码组件 
  16.  *  
  17.  * @author wbw 
  18.  * @version 1.0 
  19.  */  
  20. public abstract class DESUtil {  
  21.     static{  
  22.         Security.insertProviderAt(new BouncyCastleProvider(), 1);  
  23.     }  
  24.     /** 
  25.      * 密钥算法 <br> 
  26.      * Java 6 只支持56bit密钥 <br> 
  27.      * Bouncy Castle 支持64bit密钥 
  28.      */  
  29.     public static final String KEY_ALGORITHM = "DES";  
  30.   
  31.     /** 
  32.      * 加密/解密算法 / 工作模式 / 填充方式 
  33.      */  
  34.     public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";  
  35.   
  36.     /** 
  37.      * 转换密钥 
  38.      *  
  39.      * @param key 
  40.      *            二进制密钥 
  41.      * @return Key 密钥 
  42.      * @throws Exception 
  43.      */  
  44.     private static Key toKey(byte[] key) throws Exception {  
  45.   
  46.         // 实例化DES密钥材料  
  47.         DESKeySpec dks = new DESKeySpec(key);  
  48.   
  49.         // 实例化秘密密钥工厂  
  50.         SecretKeyFactory keyFactory = SecretKeyFactory  
  51.                 .getInstance(KEY_ALGORITHM);  
  52.   
  53.         // 生成秘密密钥  
  54.         SecretKey secretKey = keyFactory.generateSecret(dks);  
  55.   
  56.         return secretKey;  
  57.     }  
  58.   
  59.     /** 
  60.      * 解密 
  61.      *  
  62.      * @param data 
  63.      *            待解密数据 
  64.      * @param key 
  65.      *            密钥 
  66.      * @return byte[] 解密数据 
  67.      * @throws Exception 
  68.      */  
  69.     public static byte[] decrypt(byte[] data, byte[] key) throws Exception {  
  70.   
  71.         // 还原密钥  
  72.         Key k = toKey(key);  
  73.   
  74.         // 实例化  
  75.         Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);  
  76.   
  77.         // 初始化,设置为解密模式  
  78.         cipher.init(Cipher.DECRYPT_MODE, k);  
  79.   
  80.         // 执行操作  
  81.         return cipher.doFinal(data);  
  82.     }  
  83.   
  84.     /** 
  85.      * 加密 
  86.      *  
  87.      * @param data 
  88.      *            待加密数据 
  89.      * @param key 
  90.      *            密钥 
  91.      * @return byte[] 加密数据 
  92.      * @throws Exception 
  93.      */  
  94.     public static byte[] encrypt(byte[] data, byte[] key) throws Exception {  
  95.   
  96.         // 还原密钥  
  97.         Key k = toKey(key);  
  98.   
  99.         // 实例化  
  100.         Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);  
  101.   
  102.         // 初始化,设置为加密模式  
  103.         cipher.init(Cipher.ENCRYPT_MODE, k);  
  104.   
  105.         // 执行操作  
  106.         return cipher.doFinal(data);  
  107.     }  
  108.   
  109.     /** 
  110.      * 生成密钥 <br> 
  111.      * Java 6 只支持56bit密钥 <br> 
  112.      * Bouncy Castle 支持64bit密钥 <br> 
  113.      *  
  114.      * @return byte[] 二进制密钥 
  115.      * @throws Exception 
  116.      */  
  117.     public static byte[] initKey() throws Exception {  
  118.   
  119.         /* 
  120.          * 实例化密钥生成器 
  121.          *  
  122.          * 若要使用64bit密钥注意替换 将下述代码中的KeyGenerator.getInstance(CIPHER_ALGORITHM); 
  123.          * 替换为KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC"); 
  124.          */  
  125.         KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);  
  126.   
  127.         /* 
  128.          * 初始化密钥生成器 若要使用64bit密钥注意替换 将下述代码kg.init(56); 替换为kg.init(64); 
  129.          */  
  130.         kg.init(56, new SecureRandom());  
  131.   
  132.         // 生成秘密密钥  
  133.         SecretKey secretKey = kg.generateKey();  
  134.   
  135.         // 获得密钥的二进制编码形式  
  136.         return secretKey.getEncoded();  
  137.     }  
  138.       
  139.     public static byte[] initKey(String seed) throws Exception {  
  140.         KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);  
  141.         SecureRandom secureRandom = new SecureRandom(new Base64().decode(seed));    
  142.         kg.init(secureRandom);  
  143.         SecretKey secretKey = kg.generateKey();  
  144.         return secretKey.getEncoded();  
  145.     }  
  146. }  

import java.security.Key;

import java.security.SecureRandom;

import java.security.Security;

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**

  • DES安全编码组件

  • @author wbw

  • @version 1.0
    /

    public abstract class DESUtil {

    static{

    Security.insertProviderAt(new BouncyCastleProvider(), 1);

    }

    /*

    • 密钥算法 <br>
    • Java 6 只支持56bit密钥 <br>
    • Bouncy Castle 支持64bit密钥

      */

      public static final String KEY_ALGORITHM = "DES";

    /**

    • 加密/解密算法 / 工作模式 / 填充方式

      */

      public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";

    /**

    • 转换密钥

    • @param key

    •        二进制密钥

    • @return Key 密钥

    • @throws Exception

      */

      private static Key toKey(byte[] key) throws Exception {

      // 实例化DES密钥材料

      DESKeySpec dks = new DESKeySpec(key);

      // 实例化秘密密钥工厂

      SecretKeyFactory keyFactory = SecretKeyFactory

      .getInstance(KEY_ALGORITHM);

      // 生成秘密密钥

      SecretKey secretKey = keyFactory.generateSecret(dks);

      return secretKey;

      }

    /**

    • 解密

    • @param data

    •        待解密数据

    • @param key

    •        密钥

    • @return byte[] 解密数据

    • @throws Exception

      */

      public static byte[] decrypt(byte[] data, byte[] key) throws Exception {

      // 还原密钥

      Key k = toKey(key);

      // 实例化

      Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

      // 初始化,设置为解密模式

      cipher.init(Cipher.DECRYPT_MODE, k);

      // 执行操作

      return cipher.doFinal(data);

      }

    /**

    • 加密

    • @param data

    •        待加密数据

    • @param key

    •        密钥

    • @return byte[] 加密数据

    • @throws Exception

      */

      public static byte[] encrypt(byte[] data, byte[] key) throws Exception {

      // 还原密钥

      Key k = toKey(key);

      // 实例化

      Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

      // 初始化,设置为加密模式

      cipher.init(Cipher.ENCRYPT_MODE, k);

      // 执行操作

      return cipher.doFinal(data);

      }

    /**

    • 生成密钥 <br>

    • Java 6 只支持56bit密钥 <br>

    • Bouncy Castle 支持64bit密钥 <br>

    • @return byte[] 二进制密钥

    • @throws Exception

      */

      public static byte[] initKey() throws Exception {

      /*

      • 实例化密钥生成器
      • 若要使用64bit密钥注意替换 将下述代码中的KeyGenerator.getInstance(CIPHER_ALGORITHM);
      • 替换为KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC");

        */

        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);

      /*

      • 初始化密钥生成器 若要使用64bit密钥注意替换 将下述代码kg.init(56); 替换为kg.init(64);

        */

        kg.init(56, new SecureRandom());

      // 生成秘密密钥

      SecretKey secretKey = kg.generateKey();

      // 获得密钥的二进制编码形式

      return secretKey.getEncoded();

      }

    public static byte[] initKey(String seed) throws Exception {

    KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);

    SecureRandom secureRandom = new SecureRandom(new Base64().decode(seed));

    kg.init(secureRandom);

    SecretKey secretKey = kg.generateKey();

    return secretKey.getEncoded();

    }

    }

RSA加密:

[java] view plain copy print?

  1. import java.io.ByteArrayOutputStream;  
  2. import java.security.Key;  
  3. import java.security.KeyFactory;  
  4. import java.security.KeyPair;  
  5. import java.security.KeyPairGenerator;  
  6. import java.security.PrivateKey;  
  7. import java.security.PublicKey;  
  8. import java.security.SecureRandom;  
  9. import java.security.Security;  
  10. import java.security.interfaces.RSAPrivateKey;  
  11. import java.security.interfaces.RSAPublicKey;  
  12. import java.security.spec.PKCS8EncodedKeySpec;  
  13. import java.security.spec.X509EncodedKeySpec;  
  14. import java.util.HashMap;  
  15. import java.util.Map;  
  16. import java.util.UUID;  
  17.   
  18. import javax.crypto.Cipher;  
  19.   
  20. import org.bouncycastle.jce.provider.BouncyCastleProvider;  
  21. import org.bouncycastle.util.encoders.Base64;  
  22.   
  23.   
  24. /** 
  25.  * RSA安全编码组件 
  26.  *  
  27.  * @author wbw 
  28.  * @version 1.0 
  29.  */  
  30. public class RSAUtil {  
  31.     /** 
  32.      * 非对称加密密钥算法 
  33.      */  
  34.     public static final String KEY_ALGORITHM_RSA = "RSA";  
  35.   
  36.     /** 
  37.      * 公钥 
  38.      */  
  39.     private static final String RSA_PUBLIC_KEY = "RSAPublicKey";  
  40.   
  41.     /** 
  42.      * 私钥 
  43.      */  
  44.     private static final String RSA_PRIVATE_KEY = "RSAPrivateKey";  
  45.       
  46.     /** 
  47.      * RSA密钥长度  
  48.      * 默认1024位, 
  49.      * 密钥长度必须是64的倍数,  
  50.      * 范围在512至65536位之间。 
  51.      */  
  52.     private static final int KEY_SIZE = 1024;  
  53.       
  54.     static{  
  55.         Security.insertProviderAt(new BouncyCastleProvider(), 1);  
  56.     }  
  57.     /** 
  58.      * 私钥解密 
  59.      *  
  60.      * @param data 
  61.      *            待解密数据 
  62.      * @param key 
  63.      *            私钥 
  64.      * @return byte[] 解密数据 
  65.      * @throws Exception 
  66.      */  
  67.     public static byte[] decryptByPrivateKey(byte[] data, byte[] key)  
  68.             throws Exception {  
  69.   
  70.         // 取得私钥  
  71.         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);  
  72.   
  73.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);  
  74.   
  75.         // 生成私钥  
  76.         PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);  
  77.   
  78.         // 对数据解密  
  79.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  80.   
  81.         cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  82.   
  83.         int blockSize = cipher.getBlockSize();  
  84.         if(blockSize>0){  
  85.             ByteArrayOutputStream bout = new ByteArrayOutputStream(64);  
  86.             int j = 0;  
  87.             while (data.length - j * blockSize > 0) {  
  88.                 bout.write(cipher.doFinal(data, j * blockSize, blockSize));  
  89.                 j++;  
  90.             }  
  91.             return bout.toByteArray();  
  92.         }  
  93.         return cipher.doFinal(data);  
  94.     }  
  95.   
  96.     /** 
  97.      * 公钥解密 
  98.      *  
  99.      * @param data 
  100.      *            待解密数据 
  101.      * @param key 
  102.      *            公钥 
  103.      * @return byte[] 解密数据 
  104.      * @throws Exception 
  105.      */  
  106.     public static byte[] decryptByPublicKey(byte[] data, byte[] key)  
  107.             throws Exception {  
  108.   
  109.         // 取得公钥  
  110.         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);  
  111.   
  112.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);  
  113.   
  114.         // 生成公钥  
  115.         PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);  
  116.   
  117.         // 对数据解密  
  118.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  119.   
  120.         cipher.init(Cipher.DECRYPT_MODE, publicKey);  
  121.   
  122.         return cipher.doFinal(data);  
  123.     }  
  124.   
  125.     /** 
  126.      * 公钥加密 
  127.      *  
  128.      * @param data 
  129.      *            待加密数据 
  130.      * @param key 
  131.      *            公钥 
  132.      * @return byte[] 加密数据 
  133.      * @throws Exception 
  134.      */  
  135.     public static byte[] encryptByPublicKey(byte[] data, byte[] key)  
  136.             throws Exception {  
  137.   
  138.         // 取得公钥  
  139.         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);  
  140.   
  141.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);  
  142.           
  143.         PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);  
  144.   
  145.         // 对数据加密  
  146.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  147.   
  148.         cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
  149.           
  150.         int blockSize = cipher.getBlockSize();  
  151.         if(blockSize>0){  
  152.             int outputSize = cipher.getOutputSize(data.length);  
  153.             int leavedSize = data.length % blockSize;  
  154.             int blocksSize = leavedSize != 0 ? data.length / blockSize + 1  
  155.                     : data.length / blockSize;  
  156.             byte[] raw = new byte[outputSize * blocksSize];  
  157.             int i = 0,remainSize=0;  
  158.             while ((remainSize = data.length - i * blockSize) > 0) {  
  159.                 int inputLen = remainSize > blockSize?blockSize:remainSize;  
  160.                 cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);  
  161.                 i++;  
  162.             }  
  163.             return raw;  
  164.         }  
  165.         return cipher.doFinal(data);  
  166.     }  
  167.   
  168.     /** 
  169.      * 私钥加密 
  170.      *  
  171.      * @param data 
  172.      *            待加密数据 
  173.      * @param key 
  174.      *            私钥 
  175.      * @return byte[] 加密数据 
  176.      * @throws Exception 
  177.      */  
  178.     public static byte[] encryptByPrivateKey(byte[] data, byte[] key)  
  179.             throws Exception {  
  180.   
  181.         // 取得私钥  
  182.         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);  
  183.   
  184.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);  
  185.   
  186.         // 生成私钥  
  187.         PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);  
  188.   
  189.         // 对数据加密  
  190.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  191.   
  192.         cipher.init(Cipher.ENCRYPT_MODE, privateKey);  
  193.   
  194.         int blockSize = cipher.getBlockSize();  
  195.         if(blockSize>0){  
  196.             int outputSize = cipher.getOutputSize(data.length);  
  197.             int leavedSize = data.length % blockSize;  
  198.             int blocksSize = leavedSize != 0 ? data.length / blockSize + 1  
  199.                     : data.length / blockSize;  
  200.             byte[] raw = new byte[outputSize * blocksSize];  
  201.             int i = 0,remainSize=0;  
  202.             while ((remainSize = data.length - i * blockSize) > 0) {  
  203.                 int inputLen = remainSize > blockSize?blockSize:remainSize;  
  204.                 cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);  
  205.                 i++;  
  206.             }  
  207.             return raw;  
  208.         }  
  209.         return cipher.doFinal(data);  
  210.     }  
  211.   
  212.     /** 
  213.      * 取得私钥 
  214.      *  
  215.      * @param keyMap 
  216.      *            密钥Map 
  217.      * @return key 私钥 
  218.      * @throws Exception 
  219.      */  
  220.     public static Key getPrivateKey(Map<String, Key> keyMap)  
  221.             throws Exception {  
  222.         return keyMap.get(RSA_PRIVATE_KEY);  
  223.     }  
  224.   
  225.     /** 
  226.      * 取得私钥 
  227.      *  
  228.      * @param keyMap 
  229.      *            密钥Map 
  230.      * @return byte[] 私钥 
  231.      * @throws Exception 
  232.      */  
  233.     public static byte[] getPrivateKeyByte(Map<String, Key> keyMap)  
  234.             throws Exception {  
  235.         return keyMap.get(RSA_PRIVATE_KEY).getEncoded();  
  236.     }  
  237.       
  238.     /** 
  239.      * 取得公钥 
  240.      *  
  241.      * @param keyMap 
  242.      *            密钥Map 
  243.      * @return key 公钥 
  244.      * @throws Exception 
  245.      */  
  246.     public static Key getPublicKey(Map<String, Key> keyMap)  
  247.             throws Exception {  
  248.         return keyMap.get(RSA_PUBLIC_KEY);  
  249.     }  
  250.       
  251.     /** 
  252.      * 取得公钥 
  253.      *  
  254.      * @param keyMap 
  255.      *            密钥Map 
  256.      * @return byte[] 公钥 
  257.      * @throws Exception 
  258.      */  
  259.     public static byte[] getPublicKeyByte(Map<String, Key> keyMap)  
  260.             throws Exception {  
  261.         return keyMap.get(RSA_PUBLIC_KEY).getEncoded();  
  262.     }  
  263.       
  264.     /** 
  265.      * 初始化密钥 
  266.      * @param byte[] seed 种子 
  267.      * @return Map 密钥Map 
  268.      * @throws Exception 
  269.      */  
  270.     public static Map<String,Key> initKey(byte[] seed)throws Exception{  
  271.         // 实例化密钥对生成器  
  272.         KeyPairGenerator keyPairGen = KeyPairGenerator  
  273.                 .getInstance(KEY_ALGORITHM_RSA);  
  274.   
  275.         // 初始化密钥对生成器  
  276.         keyPairGen.initialize(KEY_SIZE, new SecureRandom(seed) );  
  277.   
  278.         // 生成密钥对  
  279.         KeyPair keyPair = keyPairGen.generateKeyPair();  
  280.   
  281.         // 公钥  
  282.         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
  283.   
  284.         // 私钥  
  285.         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
  286.   
  287.         // 封装密钥  
  288.         Map<String, Key> keyMap = new HashMap<String, Key>(2);  
  289.   
  290.         keyMap.put(RSA_PUBLIC_KEY, publicKey);  
  291.         keyMap.put(RSA_PRIVATE_KEY, privateKey);  
  292.   
  293.         return keyMap;  
  294.     }  
  295.       
  296.     /** 
  297.      * 初始化密钥 
  298.      * @param seed 种子 
  299.      * @return Map 密钥Map 
  300.      * @throws Exception 
  301.      */  
  302.     public static Map<String,Key> initKey(String seed)throws Exception{  
  303.         return initKey(seed.getBytes());  
  304.     }  
  305.   
  306.     /** 
  307.      * 初始化密钥 
  308.      *  
  309.      * @return Map 密钥Map 
  310.      * @throws Exception 
  311.      */  
  312.     public static Map<String, Key> initKey() throws Exception {  
  313.         return initKey(UUID.randomUUID().toString().getBytes());  
  314.     }  
  315.       
  316.     public static PublicKey getPublicRSAKey(String key) throws Exception {  
  317.         X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64.decode(key));  
  318.         KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);  
  319.         return kf.generatePublic(x509);  
  320.     }  
  321.   
  322.     public static PrivateKey getPrivateRSAKey(String key) throws Exception {  
  323.         PKCS8EncodedKeySpec pkgs8 = new PKCS8EncodedKeySpec(Base64.decode(key));  
  324.         KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);  
  325.         return kf.generatePrivate(pkgs8);  
  326.     }  
  327.   
  328. }  

import java.io.ByteArrayOutputStream;

import java.security.Key;

import java.security.KeyFactory;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.SecureRandom;

import java.security.Security;

import java.security.interfaces.RSAPrivateKey;

import java.security.interfaces.RSAPublicKey;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import java.util.HashMap;

import java.util.Map;

import java.util.UUID;

import javax.crypto.Cipher;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import org.bouncycastle.util.encoders.Base64;

/**

  • RSA安全编码组件

  • @author wbw

  • @version 1.0
    /

    public class RSAUtil {

    /*

    • 非对称加密密钥算法

      */

      public static final String KEY_ALGORITHM_RSA = "RSA";

    /**

    • 公钥

      */

      private static final String RSA_PUBLIC_KEY = "RSAPublicKey";

    /**

    • 私钥

      */

      private static final String RSA_PRIVATE_KEY = "RSAPrivateKey";

    /**

    • RSA密钥长度
    • 默认1024位,
    • 密钥长度必须是64的倍数,
    • 范围在512至65536位之间。

      */

      private static final int KEY_SIZE = 1024;

    static{

    Security.insertProviderAt(new BouncyCastleProvider(), 1);

    }

    /**

    • 私钥解密

    • @param data

    •        待解密数据

    • @param key

    •        私钥

    • @return byte[] 解密数据

    • @throws Exception

      */

      public static byte[] decryptByPrivateKey(byte[] data, byte[] key)

      throws Exception {

      // 取得私钥

      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);

      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);

      // 生成私钥

      PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

      // 对数据解密

      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

      cipher.init(Cipher.DECRYPT_MODE, privateKey);

      int blockSize = cipher.getBlockSize();

      if(blockSize>0){

      ByteArrayOutputStream bout = new ByteArrayOutputStream(64);

      int j = 0;

      while (data.length - j * blockSize > 0) {

      bout.write(cipher.doFinal(data, j * blockSize, blockSize));

      j++;

      }

      return bout.toByteArray();

      }

      return cipher.doFinal(data);

      }

    /**

    • 公钥解密

    • @param data

    •        待解密数据

    • @param key

    •        公钥

    • @return byte[] 解密数据

    • @throws Exception

      */

      public static byte[] decryptByPublicKey(byte[] data, byte[] key)

      throws Exception {

      // 取得公钥

      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);

      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);

      // 生成公钥

      PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

      // 对数据解密

      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

      cipher.init(Cipher.DECRYPT_MODE, publicKey);

      return cipher.doFinal(data);

      }

    /**

    • 公钥加密

    • @param data

    •        待加密数据

    • @param key

    •        公钥

    • @return byte[] 加密数据

    • @throws Exception

      */

      public static byte[] encryptByPublicKey(byte[] data, byte[] key)

      throws Exception {

      // 取得公钥

      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);

      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);

      PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

      // 对数据加密

      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

      cipher.init(Cipher.ENCRYPT_MODE, publicKey);

      int blockSize = cipher.getBlockSize();

      if(blockSize>0){

      int outputSize = cipher.getOutputSize(data.length);

      int leavedSize = data.length % blockSize;

      int blocksSize = leavedSize != 0 ? data.length / blockSize + 1

      : data.length / blockSize;

      byte[] raw = new byte[outputSize * blocksSize];

      int i = 0,remainSize=0;

      while ((remainSize = data.length - i * blockSize) > 0) {

      int inputLen = remainSize > blockSize?blockSize:remainSize;

      cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);

      i++;

      }

      return raw;

      }

      return cipher.doFinal(data);

      }

    /**

    • 私钥加密

    • @param data

    •        待加密数据

    • @param key

    •        私钥

    • @return byte[] 加密数据

    • @throws Exception

      */

      public static byte[] encryptByPrivateKey(byte[] data, byte[] key)

      throws Exception {

      // 取得私钥

      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);

      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);

      // 生成私钥

      PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

      // 对数据加密

      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

      cipher.init(Cipher.ENCRYPT_MODE, privateKey);

      int blockSize = cipher.getBlockSize();

      if(blockSize>0){

      int outputSize = cipher.getOutputSize(data.length);

      int leavedSize = data.length % blockSize;

      int blocksSize = leavedSize != 0 ? data.length / blockSize + 1

      : data.length / blockSize;

      byte[] raw = new byte[outputSize * blocksSize];

      int i = 0,remainSize=0;

      while ((remainSize = data.length - i * blockSize) > 0) {

      int inputLen = remainSize > blockSize?blockSize:remainSize;

      cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);

      i++;

      }

      return raw;

      }

      return cipher.doFinal(data);

      }

    /**

    • 取得私钥
    • @param keyMap
    •        密钥Map

    • @return key 私钥
    • @throws Exception

      */

      public static Key getPrivateKey(Map<String, Key> keyMap)

      throws Exception {

      return keyMap.get(RSA_PRIVATE_KEY);

      }

    /**

    • 取得私钥
    • @param keyMap
    •        密钥Map

    • @return byte[] 私钥
    • @throws Exception

      */

      public static byte[] getPrivateKeyByte(Map<String, Key> keyMap)

      throws Exception {

      return keyMap.get(RSA_PRIVATE_KEY).getEncoded();

      }

    /**

    • 取得公钥
    • @param keyMap
    •        密钥Map

    • @return key 公钥
    • @throws Exception

      */

      public static Key getPublicKey(Map<String, Key> keyMap)

      throws Exception {

      return keyMap.get(RSA_PUBLIC_KEY);

      }

    /**

    • 取得公钥
    • @param keyMap
    •        密钥Map

    • @return byte[] 公钥
    • @throws Exception

      */

      public static byte[] getPublicKeyByte(Map<String, Key> keyMap)

      throws Exception {

      return keyMap.get(RSA_PUBLIC_KEY).getEncoded();

      }

    /**

    • 初始化密钥

    • @param byte[] seed 种子

    • @return Map 密钥Map

    • @throws Exception

      */

      public static Map<String,Key> initKey(byte[] seed)throws Exception{

      // 实例化密钥对生成器

      KeyPairGenerator keyPairGen = KeyPairGenerator

      .getInstance(KEY_ALGORITHM_RSA);

      // 初始化密钥对生成器

      keyPairGen.initialize(KEY_SIZE, new SecureRandom(seed) );

      // 生成密钥对

      KeyPair keyPair = keyPairGen.generateKeyPair();

      // 公钥

      RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

      // 私钥

      RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

      // 封装密钥

      Map<String, Key> keyMap = new HashMap<String, Key>(2);

      keyMap.put(RSA_PUBLIC_KEY, publicKey);

      keyMap.put(RSA_PRIVATE_KEY, privateKey);

      return keyMap;

      }

    /**

    • 初始化密钥
    • @param seed 种子
    • @return Map 密钥Map
    • @throws Exception

      */

      public static Map<String,Key> initKey(String seed)throws Exception{

      return initKey(seed.getBytes());

      }

    /**

    • 初始化密钥
    • @return Map 密钥Map
    • @throws Exception

      */

      public static Map<String, Key> initKey() throws Exception {

      return initKey(UUID.randomUUID().toString().getBytes());

      }

    public static PublicKey getPublicRSAKey(String key) throws Exception {

    X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64.decode(key));

    KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);

    return kf.generatePublic(x509);

    }

    public static PrivateKey getPrivateRSAKey(String key) throws Exception {

    PKCS8EncodedKeySpec pkgs8 = new PKCS8EncodedKeySpec(Base64.decode(key));

    KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);

    return kf.generatePrivate(pkgs8);

    }

}












以上是 java 加密工具类(MD5、RSA、AES等加密方式) 的全部内容, 来源链接: utcz.com/z/392221.html

回到顶部