天天看點

【Java小工匠聊密碼學】--數字簽名-RSA

1、RSA數字簽名概述

使用RSA非對稱加密技術實作的數字簽名。

2、RSA數字簽名算法分類

(1)MD (MD2withRSA、MD5withRSA)

(2)SHA (SHA1withRSA、SHA256withRSA、SHA384withRSA、SHA512withRSA)

3、RSA數字簽名實作

3.1 JDK實作

package lzf.cipher.jdk;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author java小工匠
 */
public class JdkSignatureRsaUtils {
    public static final String RSA = "RSA";
    public static final String MD5withRSA = "MD5withRSA";

    // 初始化密鑰對
    public static KeyPair initKey() {
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance(RSA);
            // 512 -65536 && 64 的倍數
            generator.initialize(1024);
            return generator.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    // 擷取公鑰
    public static byte[] getPublicKey(KeyPair keyPair) {
        byte[] bytes = keyPair.getPublic().getEncoded();
        return bytes;
    }

    // 擷取公鑰
    public static String getPublicKeyStr(KeyPair keyPair) {
        byte[] bytes = keyPair.getPublic().getEncoded();
        return encodeHex(bytes);
    }

    // 擷取私鑰
    public static byte[] getPrivateKey(KeyPair keyPair) {
        byte[] bytes = keyPair.getPrivate().getEncoded();
        return bytes;
    }

    // 擷取私鑰
    public static String getPrivateKeyStr(KeyPair keyPair) {
        byte[] bytes = keyPair.getPrivate().getEncoded();
        return encodeHex(bytes);
    }

    // 簽名
    public static byte[] sign(byte[] data, byte[] privateKey, String type) {
        try {
            // 還原使用
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey);
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            PrivateKey priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            // 1、執行個體化Signature
            Signature signature = Signature.getInstance(type);
            // 2、初始化Signature
            signature.initSign(priKey);
            // 3、更新資料
            signature.update(data);
            // 4、簽名
            return signature.sign();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 驗證
    public static boolean verify(byte[] data, byte[] publicKey, byte[] sign, String type) {
        try {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            PublicKey pubKey = keyFactory.generatePublic(keySpec);
            // 1、執行個體化Signature
            Signature signature = Signature.getInstance(type);
            // 2、初始化Signature
            signature.initVerify(pubKey);
            // 3、更新資料
            signature.update(data);
            // 4、簽名
            return signature.verify(sign);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 資料準16進制編碼
    public static String encodeHex(final byte[] data) {
        return encodeHex(data, true);
    }

    // 資料轉16進制編碼
    public static String encodeHex(final byte[] data, final boolean toLowerCase) {
        final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        final char[] toDigits = toLowerCase ? DIGITS_LOWER : DIGITS_UPPER;
        final int l = data.length;
        final char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return new String(out);
    }

    public static void main(String[] args) {
        String str = "java小工匠";
        byte[] data = str.getBytes();
        // 初始化密鑰度
        KeyPair keyPair = initKey();
        byte[] publicKey = getPublicKey(keyPair);
        byte[] privateKey = getPrivateKey(keyPair);
        // 簽名
        String type = MD5withRSA;
        byte[] sign = sign(str.getBytes(), privateKey, type);
        // 驗證
        boolean b = verify(data, publicKey, sign, type);
        System.out.println("驗證:" + b);

    }
}