天天看點

加解密簽名和驗簽(RSA)

utils

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 = 64;

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

    /**
     * 擷取密鑰對
     *
     * @return 密鑰對
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(512);
        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 data 待簽名資料
     * @param privateKey 私鑰
     * @return 簽名
     */
    public static String sign(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()));
    }

    /**
     * 驗簽
     *
     * @param srcData 原始字元串
     * @param publicKey 公鑰
     * @param sign 簽名
     * @return 是否驗簽通過
     */
    public static boolean verify(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()));
    }
}

           

run

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);
            // RSA加密 待加密的文字内容
            String data = "123456";
            String encryptData = encrypt(data, getPublicKey(publicKey));
            System.out.println("加密前内容:" + data);
            System.out.println("加密後内容:" + encryptData);
            // RSA解密
            String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
            System.out.println("解密後内容:" + decryptData);

            // RSA簽名
            String sign = sign(data, getPrivateKey(privateKey));
            // RSA驗簽
            boolean result = verify(data, getPublicKey(publicKey), sign);
            System.out.print("驗簽結果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("加解密異常");
        }
}

           

result

私鑰:MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEApuh8reKKyGkvb2Z9lGtxXeNAfhUND41Xeir9g7Sqb0gxXQ8ROvPZqaRvnRlj4kyTfaX9DYWXC1+0PbQdgG8LEwIDAQABAkBEeacFE6cKV5T9aBfnNzk4Yo5H680C72LPHSoKyakOo+6U8S/wJ1Xlh+FGRT2rM/Me6w+7ujz88h505BMyaQAxAiEA3S9vciqRCrhMiDGo2Wbd7H2UaZnD3krJPK/vDyLUQEkCIQDBLfpeyrJePXMR+BVzciIu91OLBx5d76QixCj43KLoewIhALJ2KYeGDM0HcsiYuNHgi8LaeDrUFBNxZ/kNQueFhJfxAiBXR5i5P0d7gLP+yGGYuVZsdd5PEDZOJrm343zHg5gvBQIgGx9qWewJ3ypLvrLDx/acV6S7Q4Q3TOnyRjlbBCAP/Fk=
公鑰:MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKbofK3iishpL29mfZRrcV3jQH4VDQ+NV3oq/YO0qm9IMV0PETrz2amkb50ZY+JMk32l/Q2FlwtftD20HYBvCxMCAwEAAQ==
加密前内容:123456
加密後内容:AviJP8OPrBDHyQqPUare97wdGqVAQIbAjm2Mi0YgF9rHp8EmKFDKrlyUpilVBBB4+SzelZl9157eL/1kWX57Vw==
解密後内容:123456
驗簽結果:true