RSA加解密和签名验签

常用的加解密算法分三大类:非对称密钥加密算法、对称密钥加密算法、Hash加密算法

  • 非对称密钥加密算法

       常见算法:RSAElgamal、背包算法、Rabin、D-H、ECC(椭圆曲线加密算法)
       因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。
       非对称加密算法需要两个密钥:公开密钥(publickey)和私有密钥(privatekey)。公开密钥与私有密钥是一对,如果用公         开密钥对数据进行加密,只有用对应的私有密钥才能解密;如果用私有密钥对数据进行加密,那么只有用对应的公开密钥             才能解密。

  • 对称密钥加密算法

       常见算法:AESDES算法3DES算法,Blowfish算法,RC5算法,IDEA算法

       对称加密指加密和解密使用相同密钥的加密算法,有时又叫传统密码算法。
       就是加密密钥能够从解密密钥中推算出来,同时解密密钥也可以从加密密钥中推算出来。
       特点: 对称加密算法的特点是算法公开、计算量小、加密速度快、加密效率高。
       不足: 交易双方都使用同样钥匙,安全性得不到保证。

  • Hash加密算法

      常见算法:MD5SHA
      特点:不可逆


RSA 是一种常用的非对称加密,常用的方式有:

  1. 公钥加密私钥解密
  2. 私钥加密公钥解密
  3. 私钥签名公钥验签

下面使用java来实现以上方式:

1.生成密钥对实现公钥加密私钥解密、私钥加密公钥解密工具类

import com.sun.org.apache.xml.internal.security.utils.Base64;

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

/**
 * @author thyme
 * @ClassName RSAEncrypt
 * @Description TODO
 * @Date 2019/9/16 9:59
 */
public class RSAEncryptUtil {

    /**
     * 字节数据转字符串专用集合
     */
    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 随机生成密钥对
     */
    public static Map<String, String> genKeyPair() {

        //KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = null;
        Map<String, String> keyMap = new HashMap<>();

        try {
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 初始化密钥生成器,密钥大小为96-1024位
        keyPairGen.initialize(1024, new SecureRandom());
        //生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        //得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        String privateKeyString = Base64.encode(privateKey.getEncoded());
        //得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString = Base64.encode(publicKey.getEncoded());
        keyMap.put("privateKey", privateKeyString);
        keyMap.put("publicKey", publicKeyString);
        return keyMap;
    }

    /**
     * 公钥加密过程
     */
    public static byte[] publickeyEncrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公钥为空");
        }
        Cipher cipher = null;
        //使用默认RSA
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(plainTextData);
    }

    /**
     * 私钥加密过程
     */
    public static byte[] privateKeyEncrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws Exception {
        if (privateKey == null) {
            throw new Exception("加密私钥为空");
        }
        Cipher cipher = null;
        //使用默认RSA
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(plainTextData);
    }

    /**
     * 私钥解密过程
     */
    public static byte[] privateKeyDecrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
        if (privateKey == null) {
            throw new Exception("加密私钥为空");
        }
        Cipher cipher = null;
        //使用默认RSA
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(cipherData);
    }

    /**
     * 公钥解密过程
     */
    public static byte[] publicKeyDecrypt(RSAPublicKey publicKey, byte[] cipherData) throws Exception {
        if (publicKey == null) {
            throw new Exception("加密私钥为空");
        }
        Cipher cipher = null;
        //使用默认RSA
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher.doFinal(cipherData);
    }

    /**
     * 字节数据转十六进制字符串
     */
    public static String byteArrayToString(byte[] data) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
            // 取出字节的低四位 作为索引得到相应的十六进制标识符
            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
            if (i < data.length - 1) {
                stringBuilder.append(' ');
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 转换公钥
     */
    public static RSAPublicKey transformPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = Base64.decode(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        //转换公钥
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }

    /**
     * 转换私钥
     */
    public static RSAPrivateKey transformPrivateKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = Base64.decode(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        //转换私钥
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    }
}

2.签名和验签工具类

import com.sun.org.apache.xml.internal.security.utils.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA签名验签类
 */
public class RSASignature {

    /**
     * 签名算法
     */
    public static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    /**
     * RSA签名
     */
    public static String sign(String content,String privateKey,String encode) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                    Base64.decode(privateKey));

            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);

            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);

            signature.initSign(priKey);
            signature.update(content.getBytes(encode));

            byte[] signed = signature.sign();

            return Base64.encode(signed);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * RSA验签名检查
     */
    public static boolean doCheck(String content, String sign,
                                  String publicKey, String encode) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(publicKey);
            PublicKey pubKey = keyFactory
                    .generatePublic(new X509EncodedKeySpec(encodedKey));
            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);
            signature.initVerify(pubKey);
            signature.update(content.getBytes(encode));
            return signature.verify(Base64.decode(sign));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

3.测试类

import com.sun.org.apache.xml.internal.security.utils.Base64;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

/**
 * @author thyme
 * @ClassName Test
 * @Description TODO
 * @Date 2019/9/16 10:53
 */
public class Test {

    public static void main(String[] args) throws Exception {
        Map<String, String> keyPair = RSAEncryptUtil.genKeyPair();
        String publicKey = keyPair.get("publicKey");
        String privateKey = keyPair.get("privateKey");
        System.out.println("公钥:"+ publicKey);
        System.out.println("私钥:"+ privateKey);
        RSAPublicKey rsaPublicKey = RSAEncryptUtil.transformPublicKey(publicKey);
        RSAPrivateKey rsaPrivateKey = RSAEncryptUtil.transformPrivateKey(privateKey);
        System.out.println("---------公钥加密私钥解密过程----------");
        String plainText = "测试公钥加密私钥解密";
        //公钥加密过程
        byte[] cipherData = RSAEncryptUtil.publickeyEncrypt(rsaPublicKey,plainText.getBytes());
        String cipher = Base64.encode(cipherData);
        //私钥解密过程
        byte[] res = RSAEncryptUtil.privateKeyDecrypt(rsaPrivateKey, Base64.decode(cipher));
        String restr = new String(res);
        System.out.println("原文:"+ plainText);
        System.out.println("加密:" + cipher);
        System.out.println("解密:"+ restr);
        System.out.println();
        System.out.println("---------私钥加密公钥钥解密过程----------");
        plainText = "测试私钥加密公钥解密";
        //私钥加密过程
        cipherData = RSAEncryptUtil.privateKeyEncrypt(rsaPrivateKey, plainText.getBytes());
        cipher = Base64.encode(cipherData);
        //公钥解密过程
        res = RSAEncryptUtil.publicKeyDecrypt(rsaPublicKey, Base64.decode(cipher));
        restr=new String(res);
        System.out.println("原文:"+plainText);
        System.out.println("加密:"+cipher);
        System.out.println("解密:"+restr);
        System.out.println();
        System.out.println("---------私钥签名过程----------");


        String content="这是用于签名的原始字符串";
        String signstr = SignUtil.sign(content, privateKey,"utf-8");

        System.out.println("签名原串:"+ content);
        System.out.println("签名串:"+ signstr);
        System.out.println();
        System.out.println("---------公钥校验签名----------");
        System.out.println("签名原串:"+ content);
        System.out.println("签名串:"+ signstr);
        System.out.println("校验结果:"+ RSASignature.doCheck(content,signstr,publicKey,"utf-8"));
        System.out.println();
    }
}

4.测试结果

公钥:MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALnGPECMXKXiGd+x6nFZAhNj2QzR+wE7J5w7BulkX+Y6
gIGyKn/jgaja5VJBKcDVmLXpzNEeJ9xvzz/1PFckOPcCAwEAAQ==
私钥:MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAucY8QIxcpeIZ37HqcVkCE2PZDNH7
ATsnnDsG6WRf5jqAgbIqf+OBqNrlUkEpwNWYtenM0R4n3G/PP/U8VyQ49wIDAQABAkB3VrUV8hUC
KwDcBnrIXZlLw3SHG8zWuZ10aybBf01ro0XJ+SlIubZ6DE3hgFKVfTE97FMrMxfEHJPDeiwvxgjB
AiEA/cAdBGEtKu/i0Ou/lvwXJmgFl56u/Va7WklDzCdCugkCIQC7a9mr4p26i7YXenx9QYXB2JJn
HFwHuIm42VLMoIga/wIgEWhslTBVeOycEtkZe7IvpGLef1hTiO26TKdaD1diLIECIQCM32fhVpiP
2uungh2IWHOdXJfOgPZ7py19j3w46oDjKQIhANyFH3cCs00R2gU9wKIJw1LHs6Ue8w8tspCbKHnJ
7RvV
---------公钥加密私钥解密过程----------
原文:测试公钥加密私钥解密
加密:jxEN2EgoScPghpu6o9yfMwV7kyceM9R7dtdomnboioOEb35QtyAMBTb1NNQn/N/dKQseio92Ycrh
5VmLcVL3Dw==
解密:测试公钥加密私钥解密

---------私钥加密公钥钥解密过程----------
原文:测试私钥加密公钥解密
加密:Ov+CADKEegdWf8Uj4dav7MddogFfg5+LQ4zql+d0Tv8JoGYyyrnVn8utFfNhgfgnmMRFt3VUvsCj
x83WYAq4QA==
解密:测试私钥加密公钥解密

---------私钥签名过程----------
签名原串:这是用于签名的原始字符串
签名串:H55uzcC8WBv7WL1Srimtm36AmvhNDwCsonw6J1QMacgQ2O7HsXbhATlwOaXazB7XwChJ3BwCDqk1
yYbMU6eETQ==

---------公钥校验签名----------
签名原串:这是用于签名的原始字符串
签名串:H55uzcC8WBv7WL1Srimtm36AmvhNDwCsonw6J1QMacgQ2O7HsXbhATlwOaXazB7XwChJ3BwCDqk1
yYbMU6eETQ==
校验结果:true

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值