java RSA分段加密测试


最近项目中需要对前端数据进行加密,后端进行解密,于是在本地写了demo做了测试。




import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.*;

public class EnDeCode {


    public static int MAX_ENCRYPT_BLOCK = 117;
    public static int MAX_DECRYPT_BLOCK = 128;
    public static String KEY_ALGORITHM = "RSA";
    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    public static Map<String, String> param;

    public static void encryption( Map<String, Object> keyMap) throws Exception {
        RSAPublicKey publicKey = (RSAPublicKey)keyMap.get("RSAPublicKey");
        System.out.println("公钥: " + Base64.getEncoder().encodeToString(publicKey.getEncoded()));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        Map<String, String> map = new HashMap<>();
        Map<String, String> resMap = new HashMap<>();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            byte[] valueByte = value.getBytes();
            int inputLen = valueByte.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(valueByte, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(valueByte, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            String encode = Base64.getEncoder().encodeToString(encryptedData);
            resMap.put(key, encode);
        }
        param = resMap;
    }

    public static void decode(Map keyMap) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {
        RSAPrivateKey privateKey = (RSAPrivateKey)keyMap.get("RSAPrivateKey");
        System.out.println("私钥: " + Base64.getEncoder().encodeToString(privateKey.getEncoded()));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        Map<String, String> resMap = new HashMap<>();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            byte[] encryptedData = Base64.getDecoder().decode(value);
            int inputLen = encryptedData.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(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            value = new String(decryptedData);
            resMap.put(key, value);
            out.close();
        }
        param = resMap;
        return ;
    }

    public static Map<String, Object> genKeyPair() 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<String, Object> keyMap = new HashMap<String, Object>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    public static void main(String[] args) throws Exception {

        param = new HashMap<>();
        param.put("name","令狐冲");
        param.put("age","20");
        param.put("sex", "man");

        System.out.println("加密前----");

        for (Map.Entry<String, String> entry : param.entrySet() ) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println("key : " + key + " value : " + value);
        }

        System.out.println("开始加密------");
        //获取加密密钥
        Map<String, Object> keyMap = genKeyPair();
        encryption( keyMap);

        System.out.println("加密结束---");

        for (Map.Entry<String, String> entry : param.entrySet() ) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println("key : " + key + " value : " + value);
        }
        System.out.println("开始解密---");
        decode(keyMap);

        System.out.println("解密结束---");
        for (Map.Entry<String, String> entry : param.entrySet() ) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println("key : " + key + " value : " + value);
        }

    }

}

  1. 在加密测试的过程中用到了base64编码,因为通过java工具类生成的密钥,直接获取其byte,获取后是乱码
  2. 在传入的过程中需要把加密后的数据编程字符串来传, 在加密后数据变成byte[], 而在解密前需要获得数据的byte[] 如果在加密后直接用new String(data)变成字符串,再在解密后利用data.getByte()获取bytep[]会产生错误, 因此可以对加密后的数据用base64编码来避免错误。
  3. 加密长度和解密长度一定要注意,长度不对也会出现解密错误
  4. 为什么要分段加密呢? 可以试试不分段会产生什么问题
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值