RSA公私钥加解密算法java demo及应用接口调用思路和中文乱码问题解决

import java.io.ByteArrayOutputStream;
import java.security.Key;
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 java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

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

public class RSATest {

    private static final String ALGORITHM = "RSA";
    private static final String PUBLICK_EY = "PUBLICK_EY";
    private static final String PRIVATE_KEY = "PRIVATE_KEY";
    /**
     * 加密算法
     */
    private static final String CIPHER_DE = "RSA";
    /**
     * 解密算法
     */
    private static final String CIPHER_EN = "RSA";
    /**
     * 密钥长度
     */
    private static final Integer KEY_LENGTH = 1024;

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 生成秘钥对,公钥和私钥
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static Map<String, Object> genKeyPair() throws NoSuchAlgorithmException {
        Map<String, Object> keyMap = new HashMap<String, Object>();
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(KEY_LENGTH); // 秘钥字节数
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        keyMap.put(PUBLICK_EY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /**
     * 公钥加密
     *
     * @param data
     * @param publicKey
     * @return
     * @throws InvalidKeySpecException
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
        // 得到公钥
        byte[] keyBytes = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        Key key = keyFactory.generatePublic(x509EncodedKeySpec);
        // 加密数据,分段加密
        Cipher cipher = Cipher.getInstance(CIPHER_EN);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        int inputLength = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        while (inputLength - offset > 0) {
            if (inputLength - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offset, inputLength - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * 私钥解密
     *
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] data, String privateKey) throws Exception {
        // 得到私钥
        byte[] keyBytes = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec pKCS8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        Key key = keyFactory.generatePrivate(pKCS8EncodedKeySpec);
        // 解密数据,分段解密
        Cipher cipher = Cipher.getInstance(CIPHER_DE);
        cipher.init(Cipher.DECRYPT_MODE, key);
        int inputLength = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        byte[] tmp;
        while (inputLength - offset > 0) {
            if (inputLength - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(data, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offset, inputLength - offset);
            }
//            out.write(cache, 0, cache.length);
            out.write(cache);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
     * 获取公钥
     *
     * @param keyMap
     * @return
     */
    public static String getPublicKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PUBLICK_EY);
        String str = new String(Base64.encodeBase64(key.getEncoded()));
        return str;
    }

    /**
     * 获取私钥
     *
     * @param keyMap
     * @return
     */
    public static String getPrivateKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        String str = new String(Base64.encodeBase64(key.getEncoded()));
        return str;
    }

    public static void main(String[] args) throws Exception {
        Map<String, Object> keyMap = RSATest.genKeyPair();
        String publicKey = RSATest.getPublicKey(keyMap);
        String privateKey = RSATest.getPrivateKey(keyMap);
        System.out.println("公钥:" + publicKey);
        System.out.println("私钥:" + privateKey);
        // 公钥加密
        //String sourceStr = "我是私密数据要加密";
        String sourceStr ="{json:123}";
        System.out.println("加密前:" + sourceStr);
        byte[] encryptStrByte = RSATest.encryptByPublicKey(sourceStr.getBytes(), publicKey);
        byte[] btt = Base64.encodeBase64(encryptStrByte);
        String encryptStr = new String(btt);
        System.out.println("加密后:" + encryptStr);
        System.out.println("长度:" + encryptStr.length());
        // 私钥解密
        byte[] decryptStrByte = RSATest.decryptByPrivateKey(Base64.decodeBase64(Base64.encodeBase64(encryptStrByte)), privateKey);
        String sourceStr_1 = new String(decryptStrByte);
        System.out.println("解密后:" + sourceStr_1);
    }
}

原理:https://blog.csdn.net/doujinlong1/article/details/82051986

接口实际加解操作:只需要把私钥和加密后的数据一并返回给客户端,客户端再用同样的代码私钥解密即可

 

补充:解密后中文乱码的问题解决

在加密的时候对加密串中文编码

dataMapString= java.net.URLEncoder.encode("加密串","UTF-8");

在解密的时候对解密后的字符串解码

sourceStr_1= java.net.URLDecoder.decode("解密串","UTF-8");

 

 

 

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Python RSA 加密和解密文件的基本流程如下: 1. 使用 RSA 库生成公钥私钥。 2. 使用公钥对文件进行加密。 3. 使用私钥加密后的文件进行解密。 示例代码: ``` from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP # 生成公钥私钥 key = RSA.generate(2048) private_key = key.export_key() public_key = key.publickey().export_key() # 使用公钥加密文件 with open("original_file.txt", "rb") as f: original_data = f.read() cipher = PKCS1_OAEP.new(RSA.import_key(public_key)) encrypted_data = cipher.encrypt(original_data) with open("encrypted_file.bin", "wb") as f: f.write(encrypted_data) # 使用私钥解密文件 with open("encrypted_file.bin", "rb") as f: encrypted_data = f.read() cipher = PKCS1_OAEP.new(RSA.import_key(private_key)) decrypted_data = cipher.decrypt(encrypted_data) with open("decrypted_file.txt", "wb") as f: f.write(decrypted_data) ``` 请注意,上面的代码仅用于示例目的,实际应用需要注意密钥的安全存储。 ### 回答2: RSA加密算法是一种非对称加密算法,它使用一对相互关联的公钥私钥进行加解密公钥用于加密数据,而私钥用于解密数据。 在使用Python进行RSA加解密文件时,我们首先需要生成一对私钥。可以使用`rsa`库的`newkeys()`函数来生成密钥对。例如,以下代码将生成一对2048位的私钥: ``` from rsa import newkeys # 生成一对私钥 (pub_key, priv_key) = newkeys(2048) ``` 接下来,我们可以使用私钥进行文件的加解密操作。以下是一个使用RSA加解密文件的示例代码: ``` from rsa import encrypt, decrypt # 加密文件 def encrypt_file(file_path, output_path, pub_key): with open(file_path, 'rb') as file: data = file.read() enc_data = encrypt(data, pub_key) with open(output_path, 'wb') as output_file: output_file.write(enc_data) # 解密文件 def decrypt_file(file_path, output_path, priv_key): with open(file_path, 'rb') as file: enc_data = file.read() dec_data = decrypt(enc_data, priv_key) with open(output_path, 'wb') as output_file: output_file.write(dec_data) ``` 在使用以上代码时,需要指定待加密的文件路径、加密后的文件输出路径以及私钥。可以通过`pub_key.save_pkcs1()`和`priv_key.save_pkcs1()`方法将密钥保存到文件以便后续使用。 需要注意的是,RSA加密算法会对数据进行分块加解密,因此对于较大的文件,可能需要分块加密再拼接。另外,RSA加密算法的运算耗时较长,因此在实际使用可能需要将其用在对安全性要求较高的场景。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值