RSA加密、解密、簽名、驗簽的原理及方法


一、RSA加密簡介

  RSA加密是一種非對稱加密。可以在不直接傳遞密鑰的情況下,完成解密。這能夠確保信息的安全性,避免了直接傳遞密鑰所造成的被破解的風險。是由一對密鑰來進行加解密的過程,分別稱為公鑰和私鑰。兩者之間有數學相關,該加密算法的原理就是對一極大整數做因數分解的困難性來保證安全性。通常個人保存私鑰,公鑰是公開的(可能同時多人持有)。

二、RSA加密、簽名區別

  加密和簽名都是為了安全性考慮,但略有不同。常有人問加密和簽名是用私鑰還是公鑰?其實都是對加密和簽名的作用有所混淆。簡單的說,加密是為了防止信息被泄露,而簽名是為了防止信息被篡改。這里舉2個例子說明。

第一個場景:戰場上,B要給A傳遞一條消息,內容為某一指令。

RSA的加密過程如下:

(1)A生成一對密鑰(公鑰和私鑰),私鑰不公開,A自己保留。公鑰為公開的,任何人可以獲取。

(2)A傳遞自己的公鑰給B,B用A的公鑰對消息進行加密。

(3)A接收到B加密的消息,利用A自己的私鑰對消息進行解密。

  在這個過程中,只有2次傳遞過程,第一次是A傳遞公鑰給B,第二次是B傳遞加密消息給A,即使都被敵方截獲,也沒有危險性,因為只有A的私鑰才能對消息進行解密,防止了消息內容的泄露。
第二個場景:A收到B發的消息后,需要進行回復“收到”。

RSA簽名的過程如下:

(1)A生成一對密鑰(公鑰和私鑰),私鑰不公開,A自己保留。公鑰為公開的,任何人可以獲取。

(2)A用自己的私鑰對消息加簽,形成簽名,並將加簽的消息和消息本身一起傳遞給B。

(3)B收到消息后,在獲取A的公鑰進行驗簽,如果驗簽出來的內容與消息本身一致,證明消息是A回復的。

  在這個過程中,只有2次傳遞過程,第一次是A傳遞加簽的消息和消息本身給B,第二次是B獲取A的公鑰,即使都被敵方截獲,也沒有危險性,因為只有A的私鑰才能對消息進行簽名,即使知道了消息內容,也無法偽造帶簽名的回復給B,防止了消息內容的篡改。

  但是,綜合兩個場景你會發現,第一個場景雖然被截獲的消息沒有泄露,但是可以利用截獲的公鑰,將假指令進行加密,然后傳遞給A。第二個場景雖然截獲的消息不能被篡改,但是消息的內容可以利用公鑰驗簽來獲得,並不能防止泄露。所以在實際應用中,要根據情況使用,也可以同時使用加密和簽名,比如A和B都有一套自己的公鑰和私鑰,當A要給B發送消息時,先用B的公鑰對消息加密,再對加密的消息使用A的私鑰加簽名,達到既不泄露也不被篡改,更能保證消息的安全性。

  總結:公鑰加密、私鑰解密;私鑰簽名、公鑰驗簽。

三、RSA加密、簽名的方法,代碼例子如下:

import java.io.ByteArrayOutputStream;
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.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;

public class TestRSA {

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

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

    /**
     * 獲取密鑰對
     *
     * @return 密鑰對
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        return generator.generateKeyPair();
    }

    /**
     * 獲取私鑰
     *
     * @param privateKey 私鑰字符串
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 獲取公鑰
     *
     * @param publicKey 公鑰字符串
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * RSA加密
     *
     * @param data 待加密數據
     * @param publicKey 公鑰
     * @return
     */
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().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.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 獲取加密內容使用base64進行編碼,並以UTF-8為標准轉化成字符串
        // 加密后的字符串
        return new String(Base64.encodeBase64String(encryptedData));
    }

    /**
     * RSA解密
     *
     * @param data 待解密數據
     * @param privateKey 私鑰
     * @return
     */
    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.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(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的內容
        return new String(decryptedData, "UTF-8");
    }

    /**
     * 私鑰加密(未考慮明文長度超過限制的情況)
     * @param plain_text 明文
     * @param privateStr 私鑰
     * @return
     */
    public static String enWithRSAPrivateKey(String plain_text,String privateStr) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, getPrivateKey(privateStr));
            return byte2hex(cipher.doFinal(plain_text.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 公鑰解密(未考慮明文長度超過限制的情況)
     * @param plain_text 密文
     * @param publicStr 公鑰
     * @return
     */
    public static String deWithRSAPublicKey(String plain_text,String publicStr) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, getPublicKey(publicStr));
            byte[] plainText = cipher.doFinal(hex2byte(plain_text));
            return new String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * MD5withRSA簽名
     *
     * @param data 待簽名數據
     * @param privateKey 私鑰
     * @return 簽名
     */
    public static String signMD5withRSA(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(key);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /**
     * signVerifyMD5withRSA數字簽名驗證.
     *
     * @param srcData 原始字符串
     * @param publicKey 公鑰
     * @param sign 簽名
     * @return 是否驗簽通過
     */
    public static boolean signVerifyMD5withRSA(String srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }


    /**
     * SHA256withRSA簽名
     *
     * @param privateKeyStr
     *            私鑰
     * @param plain_text
     *            明文
     * @return
     */
    public static String signSha256withRSA(String plain_text,String privateKeyStr) {
        try {
            Signature Sign = Signature.getInstance("SHA256withRSA");
            PrivateKey privateKey = getPrivateKey(privateKeyStr);
            Sign.initSign(privateKey);
            Sign.update(plain_text.getBytes());
            byte[] signed = Sign.sign();
            return byte2hex(signed) ;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * SHA1WithRSA數字簽名驗證.
     *
     * @param data   數據
     * @param strHexPublicKey    公鑰
     * @param sign   簽名
     * @return true, if successful
     * @throws Exception the exception
     */
    public static boolean signVerifySHA256WithRSA(String data, String strHexPublicKey, String sign)
            throws Exception {
        try {
            PublicKey rsaPublicKey = getPublicKey(strHexPublicKey);
            //公鑰解簽
            Signature sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(rsaPublicKey);
            sig.update(data.getBytes());
            return sig.verify(hex2byte(sign));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Description:將二進制轉換成16進制字符串
     *
     * @param b
     * @return
     * @return String
     * @author name:
     */
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    /**
     * Description:將16進制字符串轉換成二進制
     * @return
     * @return String
     * @author name:
     */
    public static byte[] hex2byte(String hexString) {
        if (hexString == null || "".equals(hexString)) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * Convert char to byte
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static void main(String[] args) {
        try {
            // 生成密鑰對
            KeyPair keyPair = getKeyPair();
            String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
            String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
            System.out.println("私鑰:" + privateKey);
            System.out.println("公鑰:" + publicKey);
            String data = "張三豐";

            // RSA公鑰加密
            String encryptData = encrypt(data, getPublicKey(publicKey));
            System.out.println("公鑰加密后內容:" + encryptData);
            // RSA私鑰解密
            String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
            System.out.println("私鑰解密后內容:" + decryptData);

            // RSA私鑰加密
            String encryptData1 = enWithRSAPrivateKey(data, privateKey);
            System.out.println("私鑰加密后內容:" + encryptData1);
            // RSA公鑰解密
            String decryptData1 = deWithRSAPublicKey(encryptData1, publicKey);
            System.out.println("公鑰解密后內容:" + decryptData1);

            // RSA簽名(MD5withRSA)
            String sign = signMD5withRSA(data, getPrivateKey(privateKey));
            // RSA驗簽(MD5withRSA)
            boolean result = signVerifyMD5withRSA(data, getPublicKey(publicKey), sign);
            System.out.println("MD5withRSA驗簽結果:" + result);

            // RSA簽名(SHA256withRSA)
            String sign1 = signSha256withRSA(data, privateKey);
            // RSA驗簽(SHA256withRSA)
            boolean result1 = signVerifySHA256WithRSA(data, publicKey, sign1);
            System.out.println("SHA256withRSA驗簽結果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("加解密異常");
        }
    }
}

PS:RSA加密對明文的長度有所限制,規定需加密的明文最大長度=密鑰長度-11(單位是字節,即byte),所以在加密和解密的過程中需要分塊進行。而密鑰默認是1024位,即1024位/8位-11=128-11=117字節。所以默認加密前的明文最大長度117字節,解密密文最大長度為128字。那么為啥兩者相差11字節呢?是因為RSA加密使用到了填充模式(padding),即內容不足117字節時會自動填滿,用到填充模式自然會占用一定的字節,而且這部分字節也是參與加密的。

  密鑰長度的設置就是上面例子的第32行。可自行調整,當然非對稱加密隨着密鑰變長,安全性上升的同時性能也會有所下降。

本文轉載自:https://www.cnblogs.com/pcheng/p/9629621.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM