1.加密工具类encryption

MD5加密

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

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

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

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

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

    }

}

04-26 04:27