RSA 非对称加密算法的Java实现

开发者福利!热门AI工具限时免费用 购周边即赠Coding Plan Lite,Claude Code、Cursor等20+工具畅享,效率翻倍! 阅读详情

关于RSA的介绍Google一下很多,这里不做说明。项目开发中一般会把公钥放在本地进行加密,服务端通过私钥进行解密。Android项目开发中要用到这个加密算法,总结后实现如下:

import android.content.Context;
import android.util.Base64;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Key;
import java.security.KeyFactory;
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 javax.crypto.Cipher;


public class RSAUtil {

    /**
     * KEY_ALGORITHM
     */
    public static final String KEY_ALGORITHM = "RSA";
    /**
     * 加密Key的长度等于1024
     */
    public static int KEYSIZE = 1024;
    /**
     * 解密时必须按照此分组解密
     */
    public static int decodeLen = KEYSIZE / 8;
    /**
     * 加密时小于117即可
     */
    public static int encodeLen = 110;//(DEFAULT_KEY_SIZE / 8) - 11;

    /**
     * 加密填充方式,android系统的RSA实现是"RSA/None/NoPadding",而标准JDK实现是"RSA/None/PKCS1Padding" ,这造成了在android机上加密后无法在服务器上解密的原因
     */
    public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";


    public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];


    /**
     * 通过公钥加密
     */
    public static byte[] encryptPublicKey(byte[] encryptedData, String key) throws Exception {
        if (encryptedData == null) {
            throw new IllegalArgumentException("Input encryption data is null");
        }
        byte[] encode = new byte[]{};
        for (int i = 0; i < encryptedData.length; i += encodeLen) {
            byte[] subarray = subarray(encryptedData, i, i + encodeLen);
            byte[] doFinal = encryptByPublicKey(subarray, key);
            encode = addAll(encode, doFinal);
        }
        return encode;
    }

    /**
     * 通过私钥解密
     */
    public static byte[] decryptPrivateKey(byte[] encode, String key) throws Exception {
        if (encode == null) {
            throw new IllegalArgumentException("Input data is null");
        }
        byte[] buffers = new byte[]{};
        for (int i = 0; i < encode.length; i += decodeLen) {
            byte[] subarray = subarray(encode, i, i + decodeLen);
            byte[] doFinal = decryptByPrivateKey(subarray, key);
            buffers = addAll(buffers, doFinal);
        }
        return buffers;
    }

    /**
     * 从字符串中加载公钥
     *
     * @param publicKeyStr 公钥数据字符串
     */
    private static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
        try {
            byte[] buffer = decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            //表示根据 ASN.1 类型 SubjectPublicKeyInfo 进行编码的公用密钥的 ASN.1 编码。
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    /**
     * 从字符串中加载私钥<br>
     * 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。
     */
    private static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
        try {
            byte[] buffer = decode(privateKeyStr);
            //表示按照 ASN.1 类型 PrivateKeyInfo 进行编码的专用密钥的 ASN.1 编码。
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            return keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }


    /**
     * 用私钥解密
     */
    private static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {
        if (data == null) {
            throw new IllegalArgumentException("Input data is null");
        }
        //取得私钥
        Key privateKey = loadPrivateKey(key);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        return cipher.doFinal(data);
    }


    /**
     * 用公钥加密
     */
    private static byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
        if (data == null) {
            throw new IllegalArgumentException("Input data is null");
        }
        // 取得公钥
        Key publicKey = loadPublicKey(key);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        return cipher.doFinal(data);
    }


    /**
     * <p>
     * BASE64字符串解码为二进制数据
     * </p>
     */
    public static byte[] decode(String base64) {
        return Base64.decode(base64, Base64.DEFAULT);
    }

    /**
     * <p>
     * 二进制数据编码为BASE64字符串
     * </p>
     */
    public static String encode(byte[] bytes) {
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }


    /**
     * <p>Produces a new {@code byte} array containing the elements
     * between the start and end indices.
     *
     * <p>The start index is inclusive, the end index exclusive.
     * Null array input produces null output.
     *
     * @param array               the array
     * @param startIndexInclusive the starting index. Undervalue (&lt;0)
     *                            is promoted to 0, overvalue (&gt;array.length) results
     *                            in an empty array.
     * @param endIndexExclusive   elements up to endIndex-1 are present in the
     *                            returned subarray. Undervalue (&lt; startIndex) produces
     *                            empty array, overvalue (&gt;array.length) is demoted to
     *                            array length.
     * @return a new array containing the elements between
     * the start and end indices.
     * @since 2.1
     */
    private static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {
        if (array == null) {
            return null;
        }
        if (startIndexInclusive < 0) {
            startIndexInclusive = 0;
        }
        if (endIndexExclusive > array.length) {
            endIndexExclusive = array.length;
        }
        final int newSize = endIndexExclusive - startIndexInclusive;
        if (newSize <= 0) {
            return EMPTY_BYTE_ARRAY;
        }

        final byte[] subarray = new byte[newSize];
        System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
        return subarray;
    }

    /**
     * <p>Adds all the elements of the given arrays into a new array.
     * <p>The new array contains all of the element of {@code array1} followed
     * by all of the elements {@code array2}. When an array is returned, it is always
     * a new array.
     *
     * @param array1 the first array whose elements are added to the new array.
     * @param array2 the second array whose elements are added to the new array.
     * @return The new byte[] array.
     * @since 2.1
     */
    private static byte[] addAll(final byte[] array1, final byte... array2) {
        if (array1 == null) {
            return clone(array2);
        } else if (array2 == null) {
            return clone(array1);
        }
        final byte[] joinedArray = new byte[array1.length + array2.length];
        System.arraycopy(array1, 0, joinedArray, 0, array1.length);
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
        return joinedArray;
    }

    /**
     * <p>Clones an array returning a typecast result and handling
     * {@code null}.
     *
     * <p>This method returns {@code null} for a {@code null} input array.
     *
     * @param array the array to clone, may be {@code null}
     * @return the cloned array, {@code null} if {@code null} input
     */
    private static byte[] clone(final byte[] array) {
        if (array == null) {
            return null;
        }
        return array.clone();
    }


    /**
     * 读取密钥信息
     */
    public static String readString(InputStream in) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String readLine = null;
        StringBuilder sb = new StringBuilder();
        while ((readLine = br.readLine()) != null) {
            if (readLine.charAt(0) == '-') {
                continue;
            } else {
                sb.append(readLine);
                sb.append('\r');
            }
        }

        return sb.toString();
    }
}

使用如下:

  /**
     * 获取加密数据
     *
     * @param encryptStr 待加密字符串
     * rsa_public_key.pem 为本地公钥
     */
    public String getEncryptData(Context context, String encryptStr) {

        try {
            InputStream inPublic = context.getResources().getAssets().open("rsa_public_key.pem");
            String publicKey = readString(inPublic);
            byte[] encodedData = encryptPublicKey(encryptStr.getBytes(), publicKey);

            return encode(encodedData);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
Java对称与非对称加密解密(AES与RSA) Java对称 & 非对称加密解密(AES与RSA) 阅读详情

相关推荐

RSA非对称加密算法Java实现之输出key文件

场景:Java实现RSA,将公钥和秘钥分别输出文件,公钥用于加密,私钥用于解密。 重点要关注解密时,不能直接传String,要用byte[],所以需要加二者转换函数。 参考代码如下: package sk.ml; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream

医疗影像检索 2789

JAVA非对称加密(RSA

java项目中使用 RSA 非对称加密实现对数据的加解密和生成签名(sign),全流程记录

java_chc的博客 4914

用deepseek部署全自动的机器人--bytebot

Bytebot是一款开源AI桌面代理,提供完整的虚拟桌面环境,支持跨应用任务处理、文件管理、文档处理等复杂工作流。其技术架构包含核心控制、LLM代理、UI等组件,支持Docker和Kubernetes部署。本文演示了基于CloudStudio的部署流程,包括环境配置、Docker部署及DeepSeek API集成,实现多模型调用功能。

Kin 2456

java实现非对称加密(RSA

工具方法 package com.fhxy.utils; import org.apache.commons.net.util.Base64; import org.apache.tomcat.util.http.fileupload.IOUtils; import javax.crypto.Cipher; import java.io.ByteArrayOutputStream; import java.security.*; import java.security.interfaces.RSAPr

qq_29042647的博客 2614

Java 实现 RSA 非对称加密算法加解密和签名验签

Java 实现 RSA 非对称加密算法前言一、非对称加密算法简介二、RSA 加解密代码实例1.生成 RSA 密钥2.RSA 加解密3.测试代码三、RSA 签名验签代码实例 前言 一、非对称加密算法简介 非对称加密算法又称现代加密算法,是计算机通信安全的基石,保证了加密数据不会被破解。与对称加密算法不同,非对称加密算法需要两个密钥:公开密钥(publickey)和私有密(privatekey),因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。公钥和私钥是一对,如果用公钥对数据进行加密,只

yuanjian0814的博客 3519

RSA非对称加密 JAVA项目中实际使用方法

RSA非对称加密 JAVA项目中实际使用方法

L'Étranger的博客 1322

RSA非对称加密算法介绍及其Java实现

RSA非对称加密算法Java实现 一,非对称加密 非对称加密算法是一种密钥的保密方法。 非对称加密算法需要两个密钥:公开密钥(publickey:简称公钥)和私有密钥(privatekey:简称私钥)。公钥与私钥是一对,如果用公钥对数据进行加密,只有用对应的私钥才能解密。因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法非对称加密算法实现机密信息交换的基本过程是:甲方生成一对密钥并将公钥公开,需要向甲方发送信息的其他角色(乙方)使用该密钥(甲方的公钥)对机密信息进行加密后再发送给甲方;

淮宁湾的博客 924

Java实现非对称加密算法-RSA加解密

RSA是由三位数学家Rivest、Shamir 和 Adleman 发明的非对称加密算法,这种算法非常可靠,秘钥越长,就越难破解。 目前被破解的最长RSA秘钥是768个二进制位,长度超过768位的秘钥还无法破解,但随着计算能力的增强,以后被破解到多少位还是未知数。就目前而言,1024位的秘钥属于基本安全,2048位的秘钥属于极其安全。 RSA算法在计算机网络中被普遍应用,如:https、ssh等。 该算法还可以实现应用许可证(license),有以下几个步骤: 甲方构建密钥对(公钥和私钥,公钥给

Never Limit 1621

Java 实现 RSA 非对称加密算法:生成密钥对、保存/读取密钥、加密/解密

RSA 加密算法是一种非对称加密算法,即 RSA 拥有一对密钥(公钥 和 私钥),公钥可公开。公钥加密的数据,只能由私钥解密;私钥加密的数据只能由公钥解密。RSA 非对称加密在使用中通常公钥公开,私钥保密,使用公钥加密,私钥解密。公钥加密后的数据,只有用私钥才能解,只有服务端才有对应的私钥,因此只有服务端能解密,中途就算数据被截获,没有私钥依然不知道数据的原文内容,因此达到数据安全传输的目的。

谢TS的博客 2万+

java非对称rsa加密_Java中的非对称加密算法RSA实现

需求: 实现RSA非对称加密算法 实现: public static class RSACoder { public static final String KEY_ALGORITHM = "RSA"; private static final int KEY_SIZE = 512; private static final String PUBLIC_KEY = "RSAPublicKey"; ...

weixin_32019361的博客 120

JAVA实现RSA加密,非对称加密算法

RSA.java package org.icesnow.jeasywx.util.security; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.secur...

hellogril前端库 271

java 非对称加密算法_JAVA实现RSA加密,非对称加密算法

RSA.javapackage org.icesnow.jeasywx.util.security;import java.security.Key;import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.NoSuc...

weixin_42513387的博客 193

JAVA实现经典的非对称加密算法--RSA加解密

一、什么是非对称加密算法?   简单点讲,就是加密密钥和解密密钥不一样的一种加密算法非对称加密是指通过特定算法获取一对密钥对:公钥和私钥,公钥可以对外公开,私钥由你自己保存。我们使用其中一个密钥对数据进行加密,使用另一个密钥对加密后的数据进行解密。   优点:保密性比较好,不需要用户交换密钥,不适合于对文件加密;   缺点:加密和解密花费时间长、速度慢,适用于对少量数据进行加密。   常...

suchenbin的博客 1298

java 非对称加密算法_java 非对称加密算法RSA实现详解

现在就为大家介绍一种基于因子分解的RSA算法,这种加密算法有两种实现形式:1、公钥加密,私钥解密;2、私钥加密,公钥解密。下面就为大家分析一下实现代码,相对于DH算法,RSA显得有些简单。初始化密钥:KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");keyPairGenerator.initialize(...

weixin_31459571的博客 329

Java实现RSA非对称加密算法对数据进行加密解密

久等了,上篇文章的彩蛋部分来了,数据通信中,安全是至关重要的一环,常见的加密算法有AES对称加密算法RSA非对称加密算法,本文将详细介绍如何在Java实现RSA非对称加密算法对数据进行加密解密

牧泽的博客 2589

Java 实现 RSA 非对称加密算法-加解密和签名验签

1.非对称加密算法简介 非对称加密算法又称现代加密算法,是计算机通信安全的基石,保证了加密数据不会被破解。与对称加密算法不同,非对称加密算法需要两个密钥:公开密钥(publickey)和私有密(privatekey),因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。公钥和私钥是一对,如果用公钥对数据进行加密,只有用对应的私钥才能解密。常见算法:RSA、ECC。 RSA 加密算法是一种非对称加密算法,即 RSA 拥有一对密钥(公钥 和 私钥),公钥可公开。公钥加密的数据,只能由私钥.

迪曼奥特迦-博客 1797

JAVA实现RSA非对称加密算法

    在公钥体制中,用非对称算法来加密,运行的效率比对称加密都比较慢。这次在我的《网络安全》课上要实现这个RSA加密算法RSA是用到逆运算,要用到很多很大数据的幂乘,很容易就产生溢出。在网上搜索不到这个JAVA的源码,有也是要用另外的JAVA包的,所以就自己用JAVA写了这个算法,学JAVA刚两个多月,代码有点糙,希望大家能看懂。  import java.io.*;import 

huangshaojun的专栏 4588

Java实现RSA非对称加密算法demo工具类,RSA加密解密

Java RSA非对称加密算法demo工具类 安全性:512位的密钥被视为不安全的;768位的密钥不用担心受到除了国家安全管理(NSA)外的其他事物的危害;1024位的密钥几乎是安全的。 运算速度:慢,RSA的速度比对应同样安全级别的对称密码算法要慢1000倍左右 /** * @program: test * @description: RSA 非对称加密算法(存在加密公钥、解密私钥) 工具类 * @author: 闲走天涯 * @create: 2021-08-24 11:14 */ publi

闲走天涯的博客 842

非对称加密算法RSA算法的C++实现Java实现

非对称加密算法RSA算法的C++实现Java实现 去发现同类优质开源项目:https://gitcode.com/ 此仓库包含RSA算法在C++和Java两种编程语言中的实现代码。RSA算法是一种经典且广泛使用的非对称加密算法,能够确保数据传输的安全性。本资源中的实现代码经过验证,原理正确,能够正常运行。 内容概述 C++实现:使用C++语言对RSA算法进行实现,支持密钥生成、加密和解密功能...

gitblog_06754的博客 545
上一篇: IntelliJ IDEA UML插件
下一篇: gradle执行打包并导出Apk到指定文件夹
millerkevin
博客等级 码龄11年 7粉丝 43原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值