RSA加密解密+加签验签+生成公私钥对方法(完整版)

RSA加密解密(包含生成公私钥对方法)

package com.len.util;

import sun.misc.BASE64Decoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * 加签验签,私钥加签,公钥验签
 * 加密解密,公钥加密,私钥解密
 * 2019年7月29日13:43:25
 * @author ful
 *
 */
public class Sha1withRSAUtil {

//加签验签的公钥
private static String PUBLIC_KEY ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4L/7MhR99+yswtvSr0dKen";
public static final String KEY_ALGORITHM = "RSA";

public static final String SIGNATURE_ALGORITHM = "SHA1withRSA";

//加密解密的公钥
private static String PUBLIC_KEY2 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLL3buJCUeWdIXufBUSthNVdR6f5wZXlm/GSNKHOG=";

//加密解密的私钥
private static String PRIVATE_KEY2 = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIsvdu4kJR5Z0he58FRK2E1V1Hp/nBleWb8ZI0IZTaX5hqwbKmEkFaocswUoc4bzoHXwSNHVek8UjpNuYG7PCRmNIL2bVaXOvsv8EFAQ67mk17+aSPhHNETajRgjE7nJvZSsdLEa2fmtBHBxzNOEUT/f4wfnZ3AJ/vju/3nX9a21AgMBAAECgYB55VPPNDCd6CQrS1jDOdk9wZGYxvG69fq7dhR+6xIp7eKYECKJeMTQetn+BnNHGU7Ke2oK+19mqqZDUEN8SC26vCqpgw8cmFgqTMCYc4i7wnQaOlE20X/sonFZNz4plEIe3SQbQeBlgr/sl80QPgsAnTMFWCCZ1yX1FbSyjs4ucQJBAMJ1qRwoiO9yMUUzNEBWNar6JU4TXybG0sMimUFe6SMAzct5wR0IDD+V4O+ps1Rwu51v8ltes80/+3BFvUBiHTMCQQC3O7WTPpk1V8LRE7bn3Hjh8QdLkdAi13cKaz8Y+vraLJuiuEgnFnUTfTqRmRJ4p1ejb0XPhI+HaVEd+985P3l3AkEAi7roTWeDHiu747Grdh98aONeMwAQe1ia0cTmwuZkN9a4CeHvNeE2i+oyu4QBbEelSLfMOoOOR4oWLtKt7rmRqQJASPHCRU4EXBIGAongpMlGblwv1UvFGjnAsCslwWIY/0YG526JetYb4ZhW+qN/kPy9jNi9Z/GT2gp5OoCMyxOT3QJBAKEduCHZpY5Jre5i9s7tWm94WO7UAAxi9f93aXHuf7DKgZ8psX+/FQd59jTcajWJX9NN/aTjlRNaapLzayGvdWk=";

/**
 * 验证签名
 *
 * @param signString
 * @param sign
 * @return
 * @throws Exception
 */
public static boolean verify(String signString, String sign) throws Exception {

    byte[] data = decryptBASE64(signString);

    byte[] signs = sign.getBytes();

    try {
        //实例化
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        // 解密由base64编码的公钥
        byte[] keyBytes = decryptBASE64(PUBLIC_KEY);

        // 构造X509EncodedKeySpec对象
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

        // 取公钥对象
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        //初始化
        signature.initVerify(pubKey);

        //更新
        signature.update(signs);

        //验签
        return signature.verify(data);
    } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return false;
}

/**
 * 加密数据
 * @param originData
 * @return
 */
public static String encodeData(String originData){
    try {
        // 取公钥对象
        PublicKey pubKey = getPublicKey(PUBLIC_KEY2);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE,pubKey);
        byte[] bytesEncrypt = cipher.doFinal(originData.getBytes());
        //Base64编码
        byte[] bytesEncryptBase64 = Base64.getEncoder().encode(bytesEncrypt);
        return new String(bytesEncryptBase64);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

/**
 * 解密数据
 * @param encodeData
 * @return
 */
public static String decodeData(String encodeData){
    try {

        // 取公钥对象
        PrivateKey privateKey = getPrivateKey(PRIVATE_KEY2);

        //Base64解码
        byte[] bytesEncrypt = Base64.getDecoder().decode(encodeData);
        //加密
        Cipher cipher = Cipher.getInstance("RSA");

        cipher.init(Cipher.DECRYPT_MODE,privateKey);
        byte[] bytesDecrypt = cipher.doFinal(bytesEncrypt);
        return new String(bytesDecrypt);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

/**
 * BASE64解密
 *
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] decryptBASE64(String key) throws Exception {
    return (new BASE64Decoder()).decodeBuffer(key);
}

/**
 * 将字符串转换成公钥
 * @param key
 * @return
 * @throws Exception
 */
public static PublicKey getPublicKey(String key) throws Exception {
    byte[] keyBytes;
    keyBytes = (new BASE64Decoder()).decodeBuffer(key);
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
}

/**
 * 将字符串转换成私钥
 * @param key
 * @return
 * @throws Exception
 */
public static PrivateKey getPrivateKey(String key) throws Exception {
    byte[] keyBytes;
    keyBytes = (new BASE64Decoder()).decodeBuffer(key);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
    return privateKey;
}


public static void main(String[] args) {
   String jiami = encodeData("食之无味,弃之可惜");
    System.out.println("加密后的数据:"+jiami);
    String jiemi = decodeData(jiami);
    System.out.println("解密后的数据:"+jiemi);
}

//    public static void main(String[] args) {
//        /**
//         * 私钥加签
//         * 公钥验签
//         */
//        try {
//            String signString = "YBBNqO5nTbuNLAwm4vMkLb/h7CDDTBDuOFgXaui/2UtLl8iwXYdj/LQKvpwpdYTzawfawiidWMzMeFri4753WvlVegk5CKx9CHqo4NbAmI62c+P9yv6rZ398V/Q2NJOeM7XV+0602lbozbh2UrYIpciH14hnQ1UfJthIdRB07Y8=";
//            String sign = "memberid=1232&changAmount=123&changeWay=1";
//            boolean flag = verify(signString,sign);
//            System.out.println("验证结果:"+flag);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}

RSA加签验签

import java.io.UnsupportedEncodingException;
import java.security.*;
/**
 * 2019年7月29日13:43:39
 * ful
 * 加签  验签    签名验证:验证数据的合法来源   即验证数据来源的合法性
 * 加签:私钥
 * 验签:公钥
 */
public class Test {
    private static String privateKeyPath="储存私钥信息的文件路径";
    private static String publicKeyPath="储存公钥信息的文件路径";
    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, SignatureException {
        String data="验证该数据是否为合法的服务器发送";
        /**
         * 加签过程
         */
        PrivateKey privateKey = RSAUtil.getPrivateKey(privateKeyPath);
        Signature signature = Signature.getInstance("Sha1WithRSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes("UTF-8"));
        byte[] signed = signature.sign();
        /**
         * 验签过程
         */
        PublicKey publicKey = RSAUtil.getPublicKey(publicKeyPath);
        Signature signature2 = Signature.getInstance("Sha1WithRSA");
        signature2.initVerify(publicKey);
        signature2.update(data.getBytes("UTF-8"));
        boolean verify = signature2.verify(signed);
        System.out.println("验签结果:"+verify);
    }    
}

RSA公私钥对生成方法

package com.len.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA生成公钥私钥工具
 */
public class RsaKeysUtil{

    public static final String KEY_ALGORITHM = "RSA";
    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    public static void main(String[] args) {
        Map keyMap;
        try {
            keyMap = initKey();
            String publicKey = getPublicKey(keyMap);
            String privateKey = getPrivateKey(keyMap);

            System.out.println("生成的公钥=>" + publicKey);
            System.out.println("生成的私钥=>" + privateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getPublicKey(Map keyMap) throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return encryptBASE64(key.getEncoded());
    }

    public static String getPrivateKey(Map keyMap) throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return encryptBASE64(key.getEncoded());
    }

    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }

    public static byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }

    /**
     * RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥,即公钥,而两个大素数组合成私钥。公钥是可发布的供任何人使用,私钥则为自己所有,供解密之用。
     * 

* 解密者拥有私钥,并且将由私钥计算生成的公钥发布给加密者。加密都使用公钥进行加密,并将密文发送到解密者,解密者用私钥解密将密文解码为明文。 *

* 以甲要把信息发给乙为例,首先确定角色:甲为加密者,乙为解密者。首先由乙随机确定一个KEY,称之为密匙,将这个KEY始终保存在机器B中而不发出来;然后,由这个 KEY计算出另一个KEY,称之为公匙。这个公钥的特性是几乎不可能通过它自身计算出生成它的私钥。接下来通过网络把这个公钥传给甲,甲收到公钥后,利用公钥对信息加密,并把密文通过网络发送到乙,最后乙利用已知的私钥,就对密文进行解码了。以上就是RSA算法的工作流程。 *

* 算法实现过程为: *

* 1. 随意选择两个大的质数p和q,p不等于q,计算N=pq。 * 2. 根据欧拉函数,不大于N且与N互质的整数個数為(p-1)(q-1)。 * 3. 选择一个整数e与(p-1)(q-1)互质,并且e小于(p-1)(q-1)。 * 4. 用以下这个公式计算d:d× e ≡ 1 (mod (p-1)(q-1))。 * 5. 将p和q的记录销毁。 *

* 以上内容中,(N,e)是公钥,(N,d)是私钥。 *

*

* RSA算法的应用。 *

* 1. RSA的公钥和私钥是由KeyPairGenerator生成的,获取KeyPairGenerator的实例后还需要设置其密钥位数。 * 设置密钥位数越高,加密过程越安全,一般使用1024位。 * * KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); * keyPairGen.initialize(1024); *

*

* 2.公钥和私钥可以通过KeyPairGenerator执行generateKeyPair()后生成密钥对KeyPair, * 通过KeyPair.getPublic()和KeyPair.getPrivate()来获取。 * 动态生成密钥对,这是当前最耗时的操作,一般要2s以上。 * KeyPair keyPair = keyPairGen.generateKeyPair(); * 公钥 * PublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); * 私钥 * PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); *

* byte[] publicKeyData = publicKey.getEncoded(); * byte[] privateKeyData = publicKey.getEncoded(); * 公钥和私钥都有它们自己独特的比特编码,可以通过getEncoded()方法获取,返回类型为byte[]。通过byte[]可以再度将公钥或私钥还原出来。 */ public static Map initKey() 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 keyMap = new HashMap<>(4); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } }

你可能感兴趣的:(java安全)