RSA加密算法原理

原理

RSA加密算法原理

Java实战

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;

/**
 * @PROJECT_NAME: demo
 * @DESCRIPTION:
 */
public class RESTest {
    public static void main(String[] args) throws Exception {
        // 获取RSA算法的密钥生成器对象
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        // 设定密钥长度为1024位
        keyPairGenerator.initialize(1024);
        //生成"密钥对"对象
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        //分别获取私钥和公钥对象
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        // 使用标准Base64编码输出公钥and私钥
        System.out.println("标准Base64编码输出私钥:"+new String(Base64.getEncoder().encode(privateKey.getEncoded())));
        System.out.println("标准Base64编码输出公钥:"+new String(Base64.getEncoder().encode(publicKey.getEncoded())));
        // 安全的Base64编码输出公钥and私钥
        System.out.println("安全的Base64编码输出私钥:"+org.apache.tomcat.util.codec.binary.Base64.encodeBase64URLSafeString(privateKey.getEncoded()));
        System.out.println("安全的Base64编码输出公钥:"+org.apache.tomcat.util.codec.binary.Base64.encodeBase64URLSafeString(publicKey.getEncoded()));
        
        String data = "需要加密的内容";
        System.out.println("需要加密的内容:" + data);
        //得到要加密内容的数组
        byte[] byteData = data.getBytes(StandardCharsets.UTF_8);

        // 加密
        byte[] encryptText = encrypt(publicKey, byteData);
        System.out.println("使用安全Base64编码输出加密后的字符串:" + org.apache.tomcat.util.codec.binary.Base64.encodeBase64URLSafeString(encryptText));

        // 解密
        byte[] decryptText = decrypt(privateKey, encryptText);
        System.out.println("解密后的内容:" + new String(decryptText));
    }

    public static byte[] encrypt(RSAPublicKey publicKey, byte[] obj) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        //返回加密后的内容
        return cipher.doFinal(obj);
    }

    public static byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        //返回解密后的数组
        return cipher.doFinal(obj);
    }

}

输出结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值