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

// TODO Auto-generated method stub

HashMap map = RSAUtils.getKeys();

//生成公钥和私钥

RSAPublicKey publicKey = (RSAPublicKey) map.get("public");

RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");

//模

String modulus = publicKey.getModulus().toString();

//公钥指数

String public_exponent = publicKey.getPublicExponent().toString();

//私钥指数

String private_exponent = privateKey.getPrivateExponent().toString();

//明文

String ming = "123456789";

//使用模和指数生成公钥和私钥

RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);

RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private_exponent);

//加密后的密文

String mi = RSAUtils.encryptByPublicKey(ming, pubKey);

System.err.println(mi);

//解密后的明文

ming = RSAUtils.decryptByPrivateKey(mi, priKey);

System.err.println(ming);

}

package yyy.test.rsa;

import java.math.BigInteger;

import java.security.KeyFactory;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.NoSuchAlgorithmException;

import java.security.interfaces.RSAPrivateKey;

import java.security.interfaces.RSAPublicKey;

import java.security.spec.RSAPrivateKeySpec;

import java.security.spec.RSAPublicKeySpec;

import java.util.HashMap;

import javax.crypto.Cipher;

public class RSAUtils {

/**

* 生成公钥和私钥

* @throws NoSuchAlgorithmException

*

*/

public static HashMap getKeys() throws NoSuchAlgorithmException{

HashMap map = new HashMap();

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

keyPairGen.initialize(1024);

KeyPair keyPair = keyPairGen.generateKeyPair();

RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

map.put("public", publicKey);

map.put("private", privateKey);

return map;

}

/**

* 使用模和指数生成RSA公钥

* 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA

* /None/NoPadding】

*

* @param modulus

* 模

* @param exponent

* 指数

* @return

*/

public static RSAPublicKey getPublicKey(String modulus, String exponent) {

try {

BigInteger b1 = new BigInteger(modulus);

BigInteger b2 = new BigInteger(exponent);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);

return (RSAPublicKey) keyFactory.generatePublic(keySpec);

} catch (Exception e) {

e.printStackTrace();

return null;

}

}

/**

* 使用模和指数生成RSA私钥

* 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA

* /None/NoPadding】

*

* @param modulus

* 模

* @param exponent

* 指数

* @return

*/

public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {

try {

BigInteger b1 = new BigInteger(modulus);

BigInteger b2 = new BigInteger(exponent);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);

return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);

} catch (Exception e) {

e.printStackTrace();

return null;

}

}

/**

* 公钥加密

*

* @param data

* @param publicKey

* @return

* @throws Exception

*/

public static String encryptByPublicKey(String data, RSAPublicKey publicKey)

throws Exception {

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

// 模长

int key_len = publicKey.getModulus().bitLength() / 8;

// 加密数据长度 <= 模长-11

String[] datas = splitString(data, key_len - 11);

String mi = "";

//如果明文长度大于模长-11则要分组加密

for (String s : datas) {

mi += bcd2Str(cipher.doFinal(s.getBytes()));

}

return mi;

}

/**

* 私钥解密

*

* @param data

* @param privateKey

* @return

* @throws Exception

*/

public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)

throws Exception {

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.DECRYPT_MODE, privateKey);

//模长

int key_len = privateKey.getModulus().bitLength() / 8;

byte[] bytes = data.getBytes();

byte[] bcd = ASCII_To_BCD(bytes, bytes.length);

System.err.println(bcd.length);

//如果密文长度大于模长则要分组解密

String ming = "";

byte[][] arrays = splitArray(bcd, key_len);

for(byte[] arr : arrays){

ming += new String(cipher.doFinal(arr));

}

return ming;

}

/**

* ASCII码转BCD码

*

*/

public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {

byte[] bcd = new byte[asc_len / 2];

int j = 0;

for (int i = 0; i < (asc_len + 1) / 2; i++) {

bcd[i] = asc_to_bcd(ascii[j++]);

bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));

}

return bcd;

}

public static byte asc_to_bcd(byte asc) {

byte bcd;

if ((asc >= '0') && (asc <= '9'))

bcd = (byte) (asc - '0');

else if ((asc >= 'A') && (asc <= 'F'))

bcd = (byte) (asc - 'A' + 10);

else if ((asc >= 'a') && (asc <= 'f'))

bcd = (byte) (asc - 'a' + 10);

else

bcd = (byte) (asc - 48);

return bcd;

}

/**

* BCD转字符串

*/

public static String bcd2Str(byte[] bytes) {

char temp[] = new char[bytes.length * 2], val;

for (int i = 0; i < bytes.length; i++) {

val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);

temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');

val = (char) (bytes[i] & 0x0f);

temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');

}

return new String(temp);

}

/**

* 拆分字符串

*/

public static String[] splitString(String string, int len) {

int x = string.length() / len;

int y = string.length() % len;

int z = 0;

if (y != 0) {

z = 1;

}

String[] strings = new String[x + z];

String str = "";

for (int i=0; i

if (i==x+z-1 && y!=0) {

str = string.substring(i*len, i*len+y);

}else{

str = string.substring(i*len, i*len+len);

}

strings[i] = str;

}

return strings;

}

/**

*拆分数组

*/

public static byte[][] splitArray(byte[] data,int len){

int x = data.length / len;

int y = data.length % len;

int z = 0;

if(y!=0){

z = 1;

}

byte[][] arrays = new byte[x+z][];

byte[] arr;

for(int i=0; i

arr = new byte[len];

if(i==x+z-1 && y!=0){

System.arraycopy(data, i*len, arr, 0, y);

}else{

System.arraycopy(data, i*len, arr, 0, len);

}

arrays[i] = arr;

}

return arrays;

}

}

java

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

android

Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");

参考:

http://stackoverflow.com/questions/6069369/rsa-encryption-difference-between-java-and-android

http://stackoverflow.com/questions/2956647/rsa-encrypt-with-base64-encoded-public-key-in-android

java rsa_java中RSA加解密的实现相关推荐

  1. 与非java语言使用RSA加解密遇到的问题:algid parse error, not a sequence

    遇到的问题 在一个与Ruby语言对接的项目中,决定使用RSA算法来作为数据传输的加密与签名算法.但是,在使用Ruby生成后给我的私钥时,却发生了异常:IOException: algid parse ...

  2. 前后端java+vue 实现rsa 加解密与摘要签名算法

    RSA有两个密钥,一个是公开的,称为公开密钥:一个是私密的,称为私密密钥. 特点: 公开密钥是对大众公开的,私密密钥是服务器私有的,两者不能互推得出. 用公开密钥对数据进行加密,私密密钥可解密:私密密 ...

  3. openssl在多平台和多语言之间进行RSA加解密注意事项

    首先说一下平台和语言: 系统平台为CentOS6.3,RSA加解密时使用NOPADDING进行填充 1)使用C/C++调用系统自带的openssl 2)Android4.2模拟器,第三方openssl ...

  4. Java中的RSA加解密工具类:RSAUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt;import com.mirana.frame.utils.log.LogUtils; ...

  5. RSA加解密用途简介及java示例

    在公司当前版本的中间件通信框架中,为了防止非授权第三方和到期客户端的连接,我们通过AES和RSA两种方式的加解密策略进行认证.对于非对称RSA加解密,因为其性能耗费较大,一般仅用于认证连接,不会用于每 ...

  6. openresty 与 java RSA加解密

    上一篇搞定了openresty与java之间的aes加解密.这一篇就来说说openresty与java之间RSA的加解密.在测试的过程中.发现了与aes同样的问题.就是openresty支持的填充模式 ...

  7. RSA加解密,.net公钥/私钥兼容java

    背景介绍 之前老程序使用.net进行数据的RSA加解密,现在用JAVA重写,但是.net的公钥和私钥是xml格式,跟java的不一样,需要手动转换一下.目前网上的大部分都是java转.net.我这里来 ...

  8. Crypto++库在VS 2005中的使用——RSA加解密

    Crypto++库在VS 2005中的使用--RSA加解密 源代码:下载 一.   下载Crypto++ Library Crypto++ Library的官方网:http://www.cryptop ...

  9. java rsa 解密_Java中RSA加密解密的实现方法分析

    本文实例讲述了Java中RSA加密解密的实现方法.分享给大家供大家参考,具体如下: public static void main(String[] args) throws Exception { ...

最新文章

  1. 可视化解释11种基本神经网络架构
  2. client-go使用实例
  3. java round number,Java Number Math 类
  4. RAID扫盲篇之RAID0/RAID1/RAID5/RAID10
  5. 创建yum存储库;文件目录下存RPM包,不挂载镜像,不使用外网yum源;
  6. 博弈论进阶之Anti-SG游戏与SJ定理
  7. Linux内存卡(SD卡、TF卡)作为Swap交换空间
  8. 梁鑫:重构 - 在美股行情系统的实践
  9. Rabbit MQ 配置
  10. 我的世界pc正版好玩的服务器,都来看看好玩的服务器
  11. SSAS - 1.学习记录
  12. 大多数项目能不能投资,能不能去创业,取决于自己是站在什么高度看问题
  13. 当航运遇上区块链: 有人在砸钱,有人想上车
  14. openwrt信号弱掉线_QCA9880 openwrt 信号非常差
  15. 如何通过样本数据推断其分布
  16. nuxt 引入iconfont多色图标
  17. 一文读懂 12种卷积方法(含1x1卷积、转置卷积和深度可分离卷积等)
  18. heuristic manner
  19. 数据结构堆栈 内存堆栈_零堆栈数据科学家第二部分秋天
  20. 玩转Python脚本开发-01

热门文章

  1. mysql登录错误1045修改工具_mysql登录1045错误时 修改登录密码
  2. java自动装箱和拆箱_关于java自动装箱和自动拆箱
  3. 鸿蒙开发者有多少,鸿蒙开发者beta版本申请通过的过来人有几句话要说
  4. php业务网站资源网,企业创意业务网站模板
  5. 安卓php高级编辑器使用方法,Android Studio实战 - 编辑器介绍与使用
  6. java session 数量_java中使用session监听实现同帐号登录限制、登录人数限制
  7. Scrapy中的yield使用
  8. 语句作用_3分钟短文:Laravel模型作用域,为你“节省”更多代码
  9. spd耗材管理流程图_国药器械山东公司助力济宁医学院附属医院SPD项目成功启动...
  10. python 打开targz文件_Python下使用pandas打开excel文件并进行处理