1. 程式人生 > >Java 實現 RSA加密解密及數字簽名

Java 實現 RSA加密解密及數字簽名

RSA公鑰加密演算法是1977年由羅納德·李維斯特(Ron Rivest)、阿迪·薩莫爾(Adi Shamir)和倫納德·阿德曼(Leonard Adleman)一起提出的。當時他們三人都在麻省理工學院工作。RSA就是他們三人姓氏開頭字母拼在一起組成的。

RSA是目前最有影響力的公鑰加密演算法,它能夠抵抗到目前為止已知的絕大多數密碼攻擊,已被ISO推薦為公鑰資料加密演算法

RSA演算法是一種非對稱密碼演算法,所謂非對稱,就是指該演算法需要一對金鑰,使用其中一個加密,則需要用另一個才能解密。

閒話少說,代始如下:
package com.ss.util.secret;

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.Signature;
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 javax.crypto.Cipher;

public class RSAUtils {

    /**
     * 加密演算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * 簽名演算法
     */
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * 獲取公鑰的key
     */
    private static final String PUBLIC_KEY = "RSAPublicKey";

    /**
     * 獲取私鑰的key
     */
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * <p>
     * 生成金鑰對(公鑰和私鑰)
     * </p>
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Object> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /**
     * <p>
     * 用私鑰對資訊生成數字簽名
     * </p>
     *
     * @param data 已加密資料
     * @param privateKey 私鑰(BASE64編碼)
     *
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) throws Exception {
        byte[] keyBytes = Base64.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateK);
        signature.update(data);
        return Base64.encode(signature.sign());
    }

    /**
     * <p>
     * 校驗數字簽名
     * </p>
     *
     * @param data 已加密資料
     * @param publicKey 公鑰(BASE64編碼)
     * @param sign 數字簽名
     *
     * @return
     * @throws Exception
     *
     */
    public static boolean verify(byte[] data, String publicKey, String sign)
            throws Exception {
        byte[] keyBytes = Base64.decode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicK);
        signature.update(data);
        return signature.verify(Base64.decode(sign));
    }

    /**
     * <P>
     * 私鑰解密
     * </p>
     *
     * @param encryptedData 已加密資料
     * @param privateKey 私鑰(BASE64編碼)
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
            throws Exception {
        byte[] keyBytes = Base64.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 對資料分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
     * <p>
     * 公鑰解密
     * </p>
     *
     * @param encryptedData 已加密資料
     * @param publicKey 公鑰(BASE64編碼)
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
            throws Exception {
        byte[] keyBytes = Base64.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 對資料分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
     * <p>
     * 公鑰加密
     * </p>
     *
     * @param data 源資料
     * @param publicKey 公鑰(BASE64編碼)
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey)
            throws Exception {
        byte[] keyBytes = Base64.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 對資料加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 對資料分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * <p>
     * 私鑰加密
     * </p>
     *
     * @param data 源資料
     * @param privateKey 私鑰(BASE64編碼)
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
            throws Exception {
        byte[] keyBytes = Base64.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 對資料分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * <p>
     * 獲取私鑰
     * </p>
     *
     * @param keyMap 金鑰對
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Object> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return Base64.encode(key.getEncoded());
    }

    /**
     * <p>
     * 獲取公鑰
     * </p>
     *
     * @param keyMap 金鑰對
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Object> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return Base64.encode(key.getEncoded());
    }
}

本程式碼段中要引用到的 Base64 程式碼如下(也可以直接使用SUN 公司的 本身的Based64,這邊只是作了一次處理,弄成一個工具類):
package com.ss.util.secret;

public class Base64
{
  private static char[] Base64Code = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
   'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
    'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
    'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
    '8', '9', '+', '/' };

  private static byte[] Base64Decode = {
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, 62, -1, 63, -1, 63, 52, 53,
    54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
    -1, 0, -1, -1, -1, 0, 1, 2, 3, 4,
    5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
    25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
    29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
    39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
    49, 50, 51, -1, -1, -1, -1, -1 };

   public static String encode(byte[] b)
   {
    int code = 0;
    if (b == null)
      return null;
    StringBuffer sb = new StringBuffer((b.length - 1) / 3 << 6);
    for (int i = 0; i < b.length; i++)
     {
      code |= b[i] << 16 - i % 3 * 8 & 255 << 16 - i % 3 * 8;
      if ((i % 3 != 2) && (i != b.length - 1))
         continue;
      sb.append(Base64Code[((code & 0xFC0000) >>> 18)]);
      sb.append(Base64Code[((code & 0x3F000) >>> 12)]);
      sb.append(Base64Code[((code & 0xFC0) >>> 6)]);
      sb.append(Base64Code[(code & 0x3F)]);
      code = 0;
     }

    if (b.length % 3 > 0)
      sb.setCharAt(sb.length() - 1, '=');
    if (b.length % 3 == 1)
      sb.setCharAt(sb.length() - 2, '=');
    return sb.toString();
   }

   public static byte[] decode(String code)
   {
    if (code == null)
      return null;
    int len = code.length();
    if (len % 4 != 0)
      throw new IllegalArgumentException("Base64 string length must be 4*n");
    if (code.length() == 0)
      return new byte[0];
    int pad = 0;
    if (code.charAt(len - 1) == '=')
      pad++;
    if (code.charAt(len - 2) == '=')
      pad++;
    int retLen = len / 4 * 3 - pad;
    byte[] ret = new byte[retLen];
    for (int i = 0; i < len; i += 4)
     {
      int j = i / 4 * 3;
      char ch1 = code.charAt(i);
      char ch2 = code.charAt(i + 1);
      char ch3 = code.charAt(i + 2);
      char ch4 = code.charAt(i + 3);
       int tmp = Base64Decode[ch1] << 18 | Base64Decode[ch2] << 12 | Base64Decode[ch3] << 6 | Base64Decode[ch4];
      ret[j] = (byte)((tmp & 0xFF0000) >> 16);
      if (i < len - 4)
       {
        ret[(j + 1)] = (byte)((tmp & 0xFF00) >> 8);
        ret[(j + 2)] = (byte)(tmp & 0xFF);
       }
       else {
        if (j + 1 < retLen)
          ret[(j + 1)] = (byte)((tmp & 0xFF00) >> 8);
        if (j + 2 < retLen)
          ret[(j + 2)] = (byte)(tmp & 0xFF);
       }
     }
    return ret;
   }
}
測試程式碼:
package com.ss.util.secret;

import java.util.Map;

public class RSATester {
    static String publicKey;
    static String privateKey;

    static {
        try {
            Map<String, Object> keyMap = RSAUtils.genKeyPair();
            publicKey = RSAUtils.getPublicKey(keyMap);
            privateKey = RSAUtils.getPrivateKey(keyMap);
            System.err.println("公鑰: \n\r" + publicKey);
            System.err.println("私鑰: \n\r" + privateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        test();
        testSign();
    }

    static void test() throws Exception {
        System.err.println("公鑰加密——私鑰解密");
        String source = "這是一行要進行RSA加密的原始資料&100";
        System.out.println("\r加密前文字:\r\n" + source);
        byte[] data = source.getBytes();
        //公鑰加密
        byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
        System.out.println("加密後文字:\r\n" + new String(encodedData));
        //私鑰解密
        byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);
        String target = new String(decodedData);
        System.out.println("解密後文字: \r\n" + target);
    }

    static void testSign() throws Exception {
        System.err.println("私鑰加密——公鑰解密");
        String source = "my Test -----200---測試RSA數字簽名的原始資料";
        System.out.println("原文字:\r\n" + source);
        byte[] data = source.getBytes();
        //私鑰加密
        byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);
        System.out.println("加密後:\r\n" + new String(encodedData));
        //公鑰解密
        byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);
        String target = new String(decodedData);
        System.out.println("解密後: \r\n" + target);

        System.err.println("私鑰簽名——公鑰驗證簽名");
        String sign = RSAUtils.sign(encodedData, privateKey);
        System.err.println("簽名:\r" + sign);
        boolean status = RSAUtils.verify(encodedData, publicKey, sign);
        System.err.println("驗證結果:\r" + status);
    }
}

 

執行結果如下:

公鑰: 
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaZeGLEr/KGL7JVI+wSGRHZqmk844Zy89qmbCg9LuTclamsCZoWqo+pswi5Xmu6k4ffb9PY6W3nGA52jAOO/8x6SJCqsjKb4rapLG68SqfpyinNXANjVg+CfuPxBt1rBSUlyt3aHBcamnixJRAy5YnL8Nirnd+DsCbdMGAAR62/QIDAQAB
私鑰: 
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJpl4YsSv8oYvslUj7BIZEdmqaTzjhnLz2qZsKD0u5NyVqawJmhaqj6mzCLlea7qTh99v09jpbecYDnaMA47/zHpIkKqyMpvitqksbrxKp+nKKc1cA2NWD4J+4/EG3WsFJSXK3docFxqaeLElEDLlicvw2Kud34OwJt0wYABHrb9AgMBAAECgYEAjg4y6AxGHaGK2B5PXfgdG3yflT7pfV6B5iil1FGXy9+lThRAIj9Y5+/7XhgYTxEQ8/R0cozSSg88kb3n/RDCiDDaPNt4jWrZtmg4cFM7A+ka9sBgxL2FNeOxBAVGWgjknzIwtiCaXiQ7fDmK9reHYUZUF614OesEXU1p26qVtIECQQDTYfPslcu0GJ1u5g04wZIsDek+WdGtSSiKW3Z3MHgz9jWj8Okke7FaYJ1H2+9yrt6Bud1o0fHHRsT8Fi1EwvdxAkEAuvzEEQqdpZXPzUQOMsVSPeV+nYyyo85MhqKfNpwtl4H2naNi4Od8nQrBZPK8YFMGW0sj5+ES14KiHaXGHJ3qTQJAbyggXDX9c8xJ5YpmQ4VPN4ltMROMdmJ1RiSIrG65lyGO3ZIPF9dP0SXjL2mRhi485dz2eGuGh/NIHQQQdAtOkQJBAIwnHUawsE0Gp0Txt7qyT9x5AZhRdyx0WsOnbLLgCQRAs3qglmKA39RN1Xs2vZ9tW5xeC8Gn4BmMnrqeIIoeixkCQHRTGWVplCNyJCOarrXii5NT6oehFEMPr8DbW60s0eRWLH6aSgYrVfCP/OPQyoZb1FCJCg4aq9I/yboRVMPrhT4=
公鑰加密——私鑰解密
加密前文字:
這是一行要進行RSA加密的原始資料&100
加密後文字:
/dU^0�,h�R�p]F�<��Ԩ���: �]`g�Kg�j���L\V>���?I��8Z4�9~Sb��P�Z�68_�x`�Z�4wU(��c�=+�m���Z����#��"�eA��*�r�D�-6ÿ��E�
解密後文字: 
這是一行要進行RSA加密的原始資料&100
原文字:
my Test -----200---測試RSA數字簽名的原始資料
加密後:
X
9}��G+Y��mPB �m*���kR����v��l�+�����>E�a>b��sv[N~
B��� �
?JHl:��9�F�(ۡ�_(�yz[U�T5;T}�N/�tF,��؁;�}�p�v'�
解密後: 
my Test -----200---測試RSA數字簽名的原始資料
私鑰加密——公鑰解密
私鑰簽名——公鑰驗證簽名
S3BHxWOsWEN7Yv4+wjfzqnurss106P9hq90hNYKWLDlqHZAhFxAgn4pF7uREGWSB1TWlbQMFVP7V4rnE+TlSicO4fYIb5K/HGRA81RkJdEI5VID5w3CONn7utExbrrHLIqOEHIrOMLu8aqyCb1T5PgETy0B8+Exq3PwoWuQjX34=
true