Java 实现 RSA 非对称加解密

Java 实现 RSA 非对称加解密RSA 加解密RSA是一种非对称加密算法,拥有一对密钥(公钥和私钥),由公钥加密的数据只能由私钥解密,由私钥加密的数据只能由公钥解密。RSA 工具类public class RsaUtils { //加密算法RSA private static final String ALGORITHM = "RSA"; //密钥长度 private static final int KEY_SIZE = 1024; //公钥文件
摘要由CSDN通过智能技术生成

Java 实现 RSA 非对称加密

RSA 加解密

RSA是一种非对称加密算法,拥有一对密钥(公钥和私钥),由公钥加密的数据只能由私钥解密,由私钥加密的数据只能由公钥解密。

RSA 工具类

public class RsaUtils {
   
    //加密算法RSA
    private static final String ALGORITHM = "RSA";
    //密钥长度
    private static final int KEY_SIZE = 1024;
    //公钥文件
    private static final String PUBLIC_KEY_FILE = "PublicKey";
    //密钥文件
    private static final String PRIVATE_KEY_FILE = "PrivateKey";

    /**
     * @Title: generateKeyPair
     * @Description: TODO(生成并保存密钥对)
     * @author mervyn
     * @date  2020年05月21日 10:59:07
     * @param
     * @return void
     * @throws
    */
    public static void generateKeyPair() {
   
        //获取一个RSA算法的密钥生成实例
        KeyPairGenerator keyPairGenerator = null;
        try {
   
            keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
   
            e.printStackTrace();
        }

        //初始化密钥长度
        keyPairGenerator.initialize(KEY_SIZE);

        //生成密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        //公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        //私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        //编码处理,方便保存
        String publicKeyStr = new BASE64Encoder().encode(publicKey.getEncoded());
        String privateKeyStr = new BASE64Encoder().encode(privateKey.getEncoded());

        //保存输出流
        BufferedWriter pubBw = null;
        BufferedWriter priBw = null;
        try {
   
            pubBw = new BufferedWriter(new FileWriter(PUBLIC_KEY_FILE));
            priBw = new BufferedWriter(new FileWriter(PRIVATE_KEY_FILE));
            pubBw.write(publicKeyStr);
            priBw.write(privateKeyStr);
            pubBw.flush();
            priBw.flush();
        } catch (IOException e) {
   
            e.printStackTrace();
        } finally {
   
            if (pubBw != null) {
   
                try {
   
                    pubBw.close();
                } catch (IOException e) {
   
                    e.printStackTrace();
                }
            }
            if (priBw != null) {
   
                try {
   
                    priBw.close();
                } catch 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值