【Java----加密解密】第十二章 非对称加密算法-RSA

本文详细解析了RSA这一经典非对称加密算法的特点与实现,包括其加解密流程、安全性对比DH算法的优势,以及使用JDK进行RSA加解密的具体代码实现。

注意:本节内容主要参考自《Java加密与解密的艺术(第2版)》第8章“高等加密算法--非对称加密算法”

12.1、RSA(最经典的非对称加密算法)

特点:

  • 使用一套密钥即可完成加解密(与DH不同)
  • 与DH不同的第二点是,RSA自己可以完成加解密,而DH需要依赖于对称加密算法
  • “私钥加密,公钥解密”或“公钥加密,私钥解密”
  • 公钥长度远小于私钥长度(对下边的代码进行测试,自己比较结果)

加解密流程:

1)发送方(假设为甲方)构建密钥对,自己保留私钥,将公钥发送给接收方(假设为乙方)

2)甲方使用密钥对消息进行加密,乙方使用公钥对消息解密(“私钥加密,公钥解密”)或者乙方使用公钥对消息进行加密,甲方使用私钥对消息解密(“公钥加密,私钥解密”)

注意:公钥加密方式存在安全隐患,如果需要更加安全的方式,就需要甲乙双方均存一份密钥对,仅仅使用“私钥加密,公钥解密”的方式,这种方式与DH类似,但是不同,在DH中甲乙双方各自保留着自己的公钥+私钥,而更安全的RSA是甲乙方法均保存着自己的私钥与对方的公钥,这是RSA与DH的第三点不同。

实现方式:

  • JDK(工作模式只有ECB,填充方式可以采用PKCS1Padding,没有PKCS5Padding,密钥长度:512~65536(64的整数倍))
  • Bouncy Castle(BC,工作模式没有,填充方式可以采用PKCS1Padding,没有PKCS7Padding,密钥长度:512~65536(64的整数倍))

基于JDK实现的RSA加解密代码:

package RSAJDK;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
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.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.commons.codec.binary.Base64;

/**
 * 基于JDK的RSA算法,工作模式采用ECB
 */
public class RSAJDK {
    private static final String ENCODING = "UTF-8";
    private static final String KEY_ALGORITHM = "RSA";//非对称加密密钥算法
    private static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";//加解密算法 格式:算法/工作模式/填充模式
    private static final int KEY_SIZE = 512;//非对称密钥长度(512~1024之间的64的整数倍)
    
    /**
     * 还原公钥
     * @param pubKey 二进制公钥
     */
    public static PublicKey toPublicKey(byte[] pubKey) throws NoSuchAlgorithmException, 
                                                              InvalidKeySpecException{
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);//密钥工厂
        return keyFactory.generatePublic(new X509EncodedKeySpec(pubKey));//还原公钥
    }
    
    /**
     * 还原私钥
     * @param priKey 二进制私钥
     */
    public static PrivateKey toPrivateKey(byte[] priKey) throws NoSuchAlgorithmException, 
                                                                InvalidKeySpecException{
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);//密钥工厂
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(priKey));//还原私钥
    }
    
    /**
     * 生成甲方密钥对
     */
    public static KeyPair initKey() throws NoSuchAlgorithmException{
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);//密钥对生成器
        keyPairGenerator.initialize(KEY_SIZE);//指定密钥长度
        KeyPair keyPair = keyPairGenerator.generateKeyPair();//生成密钥对
        return keyPair;
    }
    
    /**
     * 私钥加密
     * @param data     待加密数据
     * @param keyByte  私钥
     */
    public static byte[] encryptPriKey(String data, byte[] keyByte) throws NoSuchAlgorithmException, 
                                                                           InvalidKeySpecException, 
                                                                           NoSuchPaddingException, 
                                                                           InvalidKeyException, 
                                                                           IllegalBlockSizeException, 
                                                                           BadPaddingException, 
                                                                           UnsupportedEncodingException {
        PrivateKey priKey = toPrivateKey(keyByte);//还原私钥

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, priKey);//设置加密模式并且初始化key
        return cipher.doFinal(data.getBytes(ENCODING));
    }
    
    /**
     * 公钥加密
     * @param data        待加密数据
     * @param keyByte    公钥
     */
    public static byte[] encryptPubKey(String data, byte[] keyByte) throws NoSuchAlgorithmException, 
                                                                           InvalidKeySpecException, 
                                                                           NoSuchPaddingException, 
                                                                           InvalidKeyException, 
                                                                           IllegalBlockSizeException, 
                                                                           BadPaddingException, 
                                                                           UnsupportedEncodingException {
        PublicKey pubKey = toPublicKey(keyByte);//还原公钥

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);//设置加密模式并且初始化key
        return cipher.doFinal(data.getBytes(ENCODING));
    }
    
    /**
     * 私钥解密
     * @param data        待解密数据
     * @param keyByte    私钥
     */
    public static byte[] decryptPriKey(byte[] data, byte[] keyByte) throws NoSuchAlgorithmException, 
                                                                           InvalidKeySpecException, 
                                                                           NoSuchPaddingException, 
                                                                           InvalidKeyException, 
                                                                           IllegalBlockSizeException, 
                                                                           BadPaddingException {
        PrivateKey priKey = toPrivateKey(keyByte);//还原私钥
        
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        return cipher.doFinal(data);
    }
    
    /**
     * 公钥解密
     * @param data
     * @param keyByte    公钥
     */
    public static byte[] decryptPubKey(byte[] data, byte[] keyByte) throws NoSuchAlgorithmException, 
                                                                           InvalidKeySpecException, 
                                                                           NoSuchPaddingException, 
                                                                           InvalidKeyException, 
                                                                           IllegalBlockSizeException, 
                                                                           BadPaddingException {
        PublicKey pubKey = toPublicKey(keyByte);//还原公钥
        
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, pubKey);
        return cipher.doFinal(data);
    }
    
    /**
     * 获取公钥
     */
    public static byte[] getPublicKey(KeyPair keyPair){
        return keyPair.getPublic().getEncoded();
    }
    
    /**
     * 获取私钥
     */
    public static byte[] getPrivateKey(KeyPair keyPair){
        return keyPair.getPrivate().getEncoded();
    }
    
    /**
     * 测试
     */
    public static void main(String[] args) throws NoSuchAlgorithmException, 
                                                  InvalidKeyException, 
                                                  InvalidKeySpecException, 
                                                  NoSuchPaddingException, 
                                                  IllegalBlockSizeException, 
                                                  BadPaddingException, 
                                                  UnsupportedEncodingException{
        byte[] pubKey1;//甲方公钥
        byte[] priKey1;//甲方私钥
        
        /*********************测试是否可以正确生成以上2个key*********************/
        KeyPair keyPair1 = RSAJDK.initKey();//生成甲方密钥对
        pubKey1 = RSAJDK.getPublicKey(keyPair1);
        priKey1 = RSAJDK.getPrivateKey(keyPair1);
        
        System.out.println("甲方公钥pubKey1-->"+Base64.encodeBase64String(pubKey1)+"@@pubKey1.length-->"+pubKey1.length);
        System.out.println("甲方私钥priKey1-->"+Base64.encodeBase64String(priKey1)+"@@priKey1.length-->"+priKey1.length);
        
        /*********************测试甲方使用私钥加密数据向乙方发送,乙方使用公钥解密数据*********************/
        System.out.println("甲方-->乙方");
        String data = "找一个好姑娘啊!";
        byte[] encodeStr = RSAJDK.encryptPriKey(data, priKey1);
        System.out.println("甲方加密后的数据-->"+Base64.encodeBase64String(encodeStr));
        byte[] decodeStr = RSAJDK.decryptPubKey(encodeStr, pubKey1);
        System.out.println("乙方解密后的数据-->"+new String(decodeStr,"UTF-8"));
        
        /*********************测试乙方使用私钥加密数据向甲方发送,甲方使用公钥解密数据*********************/
        System.out.println("乙方-->甲方");
        String data2 = "找一个好姑娘啊!";
        byte[] encodeStr2 = RSAJDK.encryptPubKey(data2, pubKey1);
        System.out.println("乙方加密后的数据-->"+Base64.encodeBase64String(encodeStr2));
        byte[] decodeStr2 = RSAJDK.decryptPriKey(encodeStr2, priKey1);
        System.out.println("甲方解密后的数据-->"+new String(decodeStr2,"UTF-8"));
    }
}

 

注意:

自己若看了DH算法,试着比较一下RSA算法与DH的区别,并使这些一下更安全的RSA算法(生成两个密钥对,其实就是在上述的代码中再添加一个乙方的密钥对生成方法即可)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值