文档章节

RSA 加密解密

夜黑人模糊灬
 夜黑人模糊灬
发布于 2017/08/29 09:59
字数 669
阅读 12
收藏 1
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
 * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
 * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
 */
public class RSAEncrypterTest {

    /**
     * 加密算法RSA
     */
    private static final String KEY_ALGORITHM = "RSA";
    /**
     * 签名算法
     */
    private static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";//RSA是加密方法,ECB是加密模式,PKCS1Padding是填充方式
    /**
     * 私钥
     * openssl pkcs8 -topk8 -inform PEM -in p_key.pem -outform PEM -nocrypt
     */
    private static final String PRIVATE_KEY = "" + "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAPMhwl+bv8MlboJf" + "u6W5ec0SoQQxsHn8fHmfIEvWpLc1K6uiycJfOR4nHz2hRPMquw5uuz/yWvDUkrcl" + "dabWKuI9tq2kv8Kxv1M2E+9DE+ySCKqsrAp/XZMlsy8DP+fkPEATQRv4EUkH5eD6" + "x+0BlOpbZVtXdC7vyWeGSPOwldiRAgMBAAECgYBZ5ozB34xbszaWnKF9GQURsCa7" + "r0frA1Jfglhl0ntbhxybvXjPF3i+Tob9uekN5Sn/nzA75/h6fo+1ivNi+mQmRVf2" + "6h5/kfRYy0y3RNPFOTnd6B36etUx6EpzXlpT/q+igRqlu4ts4P1heBGOdqtLlSp9" + "0KqHnjieFEgMpMschQJBAP1HdyYoSJwbYd5J3DpUIEpfjIn1MkJ2OyrEk6MQypqF" + "G8ilOJCMsFFW8oY6pPPYT9z+3NwPqxz+UWU9Kv9WjXcCQQD1vmNcAB4eg99uEExs" + "WOHEcWFNZ654K/iJ915A/c7cIJSBkoe80kqDYg+UXuY/r7ZuUi3zPSECZzs4ge8H" + "+yw3AkEAzPSM1WLZxwFdhAzO2qCC9Mw3JNg3EJMuM+CY++a1nK7EGeyhRk+iyl+K" + "p9ZC71QG5HWU8br4I+EkqsEBz1gR5wJAf8/kEaemAq0H+lDTzs5zrh5iQ0YXwjzs" + "aaWVCix3+JmhY7r4ika9ppPMEplBHAKh2cM4TviOQJe8f2llDzueBQJBAPaYpKS7" + "fTh7xi5WkJrStcNVOVgThxgmIEg3mGTztBMe87WTgUAPMr4N9gewNf+5jx231cFB" + "3gYkkPgWNOYL/2Y=";
    /**
     * 公钥
     */
    private static final String PUBLIC_KEY = "" + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDzIcJfm7/DJW6CX7uluXnNEqEE" + "MbB5/Hx5nyBL1qS3NSurosnCXzkeJx89oUTzKrsObrs/8lrw1JK3JXWm1iriPbat" + "pL/Csb9TNhPvQxPskgiqrKwKf12TJbMvAz/n5DxAE0Eb+BFJB+Xg+sftAZTqW2Vb" + "V3Qu78lnhkjzsJXYkQIDAQAB";
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    @Test
    public void decodeTest() throws Exception {
        String data = "g08ZvPcrV+k8Fh1wJ8BRGDGJWOV6pm6aq6G+Q0vgfS4SQXAXx1DI9r489cs9krBu/2Okm1g4tvqzESWHW/" + "HFqFdsgYAHluN/x6mOAx4WTYYw5XlWCYdEUhhfHeUhZi9WR0omKCrFgSfyNWx5OPy/35PSLuvl5df5E30ewejDM9+tV8" + "pAr/lDQD30BE/XwH2Hvc1EdsZ54kncK2v7lOvmMNR3PmjVsryQNnuy4kqUY5yOqi7VJlf8atOheCUe+psrnJauDc32m/" + "R99hE1UhD/R8j7Df9ZptbL/37GOpyeCyRrBpGaSjUDJ2YmiS3AnA2hoeDVV5eT72J8P5EPFYuDGQ==";
        PrivateKey privateKey = getPrivateKey(PRIVATE_KEY);
        Cipher vDeCipher = Cipher.getInstance(CIPHER_ALGORITHM);
        vDeCipher.init(Cipher.DECRYPT_MODE, privateKey);
        //私钥解密
        byte[] decrypted = autoFinal(Base64.decodeBase64(data.getBytes()), vDeCipher, MAX_DECRYPT_BLOCK);
        System.out.println("解密后:" + new String(decrypted, "utf-8"));
    }

    @Test
    public void baseTest() throws Exception {
        PrivateKey privateKey = getPrivateKey(PRIVATE_KEY);
        PublicKey publicKey = getPublicKey(PUBLIC_KEY);
        String data = "RSA加密明文最大长度117字节,解密要求密文最大长度为128字节,所以在加密和解密的过程中需要分块进行。";
        //--
        Cipher pEnCipher = Cipher.getInstance(CIPHER_ALGORITHM);//java默认"RSA"="RSA/ECB/PKCS1Padding"
        pEnCipher.init(Cipher.ENCRYPT_MODE, publicKey);
        Cipher vDeCipher = Cipher.getInstance(CIPHER_ALGORITHM);
        vDeCipher.init(Cipher.DECRYPT_MODE, privateKey);
        //--
        Cipher vEnCipher = Cipher.getInstance(CIPHER_ALGORITHM);
        vEnCipher.init(Cipher.ENCRYPT_MODE, privateKey);
        Cipher pDeCipher = Cipher.getInstance(CIPHER_ALGORITHM);
        pDeCipher.init(Cipher.DECRYPT_MODE, publicKey);
        //公钥加密
        byte[] encrypted = Base64.encodeBase64(autoFinal(data.getBytes("utf-8"), pEnCipher, MAX_ENCRYPT_BLOCK));
        System.out.println("加密后:" + new String(encrypted));
        //私钥解密
        byte[] decrypted = autoFinal(Base64.decodeBase64(encrypted), vDeCipher, MAX_DECRYPT_BLOCK);
        System.out.println("解密后:" + new String(decrypted, "utf-8"));
        //私钥加密
        byte[] encrypted2 = Base64.encodeBase64(autoFinal(data.getBytes("utf-8"), vEnCipher, MAX_ENCRYPT_BLOCK));
        System.out.println("加密后:" + new String(encrypted2));
        //公钥解密
        byte[] decrypted2 = autoFinal(Base64.decodeBase64(encrypted2), pDeCipher, MAX_DECRYPT_BLOCK);
        System.out.println("解密后:" + new String(decrypted2, "utf-8"));
    }

    /**
     * 将base64编码后的公钥字符串转成PublicKey实例
     */
    private static PublicKey getPublicKey(String publicKey) throws Exception {
        byte[] keyBytes = new Base64().decode(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * 将base64编码后的私钥字符串转成PrivateKey实例
     */
    private static PrivateKey getPrivateKey(String privateKey) throws Exception {
        byte[] keyBytes = new Base64().decode(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }

    private static byte[] autoFinal(byte[] data, Cipher cipher, int blockSize) throws Exception {
        int inputLen = data.length;
        byte[] rs;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > blockSize) {
                    cache = cipher.doFinal(data, offSet, blockSize);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * blockSize;
            }
            rs = out.toByteArray();
        }
        return rs;
    }
}

© 著作权归作者所有

共有 人打赏支持
夜黑人模糊灬
粉丝 7
博文 69
码字总数 45164
作品 0
程序员
勒索软件加密方式

勒索软件的加密方式 spora勒索软件加密方式 以上加密方式的说明: 1 RSA 加密方式为非对称加密,需要公钥和私钥各不相同。AES对称加密,加密解密使用同一个密钥。 2 spora勒索软件, 产生一对...

Alyoyojie
2017/03/02
0
0
iOS,一行代码进行RSA、DES 、AES、MD5加密、解密

iOS,一行代码进行RSA、DES 、AES、MD5加密、解密 加密的Demo,欢迎下载 java端的加密解密,读者可以看我同事的这篇文章http://www.jianshu.com/p/98569e81cc0b 最近做了一个移动项目,是有服...

法斗斗
2016/05/31
81
0
iOS,一行代码进行RSA、DES 、AES、MD5加密、解密

加密的Demo 最近做了一个移动项目,是有服务器和客户端类型的项目,客户端是要登录才行的,服务器也会返回数据,服务器是用Java开发的,客户端要同时支持多平台(Android、iOS),在处理iOS...

hejunbinlan
2016/07/28
23
0
javax.crypto.BadPaddingException: Blocktype mis...

错误:javax.crypto.BadPaddingException: Blocktype mismatch 1.最近做RSA加密用于增强android客户机与服务器(JavaEE)数据传输的安全性。发现在andorid上生成的(密钥对由服务器在windows下...

cwalet
2011/11/23
0
3
使用Hutool处理RSA等非对称加密

介绍 Hutool工具是一个国产开源Java工具集,旨在简化Java开发中繁琐的过程,Hutool-crypto模块便是针对JDK加密解密做了大大简化。 此文主要介绍利用Hutool-crypto简化非对称加密解密。 对于非...

路小磊
2017/08/24
0
22

没有更多内容

加载失败,请刷新页面

加载更多

下一页

nginx访问日志-日志切割-静态文件不记录日志和过期时间

nginx访问日志: vim /usr/local/nginx/conf/nginx.conf #搜索log_format 该字段定义日志格式,默认如下: #combined_realip日志格式的名字,可随意定义; 定义访问日志: 需在虚拟主机配置文...

ZHENG-JY
5分钟前
0
0
180.mariadb 主从复制

参考:https://blog.csdn.net/chengxuzaza/article/details/62042920 睡觉睡觉,明天写 1.效果 当主库中数据有变化的时候,从库就自动同步 2. 环境要求 至少两台 linux服务器 (教程:https...

Lucky_Me
15分钟前
0
0
erlng file id3v1 id3v1.1

%% ---%% Excerpted from "Programming Erlang",%% published by The Pragmatic Bookshelf.%% Copyrights apply to this code. It may not be used to create training material, %% ......

xueyuse0012
16分钟前
1
0
RabbitMq的安装

环境Centos6.5 32位 JDK 1.7.8 Jdk的卸载 rpm -qa|grep jdk yum –y remove 上边的安装包 JDK的安装 Rpm –ivh jdk安装包 配置环境变量 export JAVA_BIN=/usr/java/jdk1.7.0_80/bin export J......

DemonsI
20分钟前
0
0
http和https协议

HTTPS全称为Hypertext Transfer Protocol over Secure Socket Layer,中文含义为“超文本传输协议在安全加密字层”,简单来说就是加密数据传输,通俗的说就是安全连接。 HTTPS安全超文本传输...

寰宇01
26分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部