关于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 "";
}

RSA 非对称加密算法的Java实现的更多相关文章

  1. RSA非对称加密算法实现:Java

    RSA是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.当时他们三人都在麻省理工学院工作.RSA ...

  2. SSH加密原理、RSA非对称加密算法学习与理解

    首先声明一下,这里所说的SSH,并不是Java传统的三大框架,而是一种建立在应用层和传输层基础上的安全外壳协议,熟悉Linux的朋友经常使 用到一 个SSH Secure Shell Cilent的工 ...

  3. RSA非对称加密算法实现:Python

    RSA是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.当时他们三人都在麻省理工学院工作.RSA ...

  4. RSA非对称加密算法实现:Golang

    RSA是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.当时他们三人都在麻省理工学院工作.RSA ...

  5. RSA非对称加密算法实现:C#

    RSA是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.当时他们三人都在麻省理工学院工作.RSA ...

  6. RSA—非对称加密算法

    RSA:非对称加密算法加解密原理如下:已知:p,q,n,e,d,m,c其中:p与q互为大质数,n=p*q 公钥Pk(n,e):加密使用,是公开的 私钥Sk(n,d):解密使用,不公开 c:明文 m:密 ...

  7. RSA非对称加密算法实现过程

    RSA非对称加密算法实现过程 非对称加密算法有很多,RSA算法就是其中比较出名的算法之一,下面是具体实现过程 <?php /** */ class Rsa { /** * private key ...

  8. .NET Core加解密实战系列之——RSA非对称加密算法

    目录 简介 功能依赖 生成RSA秘钥 PKCS1格式 PKCS8格式 私钥操作 PKCS1与PKCS8格式互转 PKCS1与PKCS8私钥中提取公钥 PEM操作 PEM格式密钥读取 PEM格式密钥写入 ...

  9. RSA非对称加密(java实例代码)

    使用RSA对WebService传递的信息加密解密的基本思想是:服务器端提供一个WebService方法String getServerPublicKey(),客户端可以以此得到服务器端的公钥,然后使 ...

随机推荐

  1. Sql sever DateDiff 函数

    函数: DATEDIFF(datepart,startdate,enddate) 具体实例: --相差年数 结果0 SELECT DATEDIFF(yy,'2008-12-29','2008-12-1 ...

  2. JS 语句

    JS 语句 JavaScript 语句 JavaScript 语句向浏览器发出的命令.语句的作用是告诉浏览器该做什么. 下面的 JavaScript 语句向 id="demo" 的 ...

  3. Linxu:在Linux下访问Windows的共享目录

    在 Windows xp 上设置一个共享目录 共享目录:d:\myfiles 在 Linux 下安装 samba-client 客户端 yum install samba-client 安装 cifs ...

  4. rasa结合kashgari训练数据时,out of memory错误

    这两天新搬办公室,网络不好用,将就了.博客园也上不了,github也上不了了,工作效率降低不少.今天遇到同事使用rasa用机器人项目的问题,一个4核的Tesla K80 GPU,性能照说不差,但一运行 ...

  5. Codeforces Round #583 (Div. 1 + Div. 2, based on Olympiad of Metropolises)

    传送门 A. Optimal Currency Exchange 枚举一下就行了. Code #include <bits/stdc++.h> using namespace std; t ...

  6. 80道最新java基础部分面试题(六)

    自己整理的面试题,希望可以帮到大家,需要更多资料的可以私信我哦,大家一起学习进步! 59.ArrayList和Vector的区别 答: 这两个类都实现了List接口(List接口继承了Collecti ...

  7. AD软件笔记

    问题1:不同网络的线可以重叠在一起         解决方法1: 在AD中,可以通过   SHIFT+R  快捷键     设置 三种布线模式(忽略 避开 或者 推挤) 解决方法2: 设置规则的Ele ...

  8. mysql索引类型:FULLTEXT、NORMAL、SPATIAL、UNIQUE的详细介绍(转)

    Normal 普通索引 表示普通索引,大多数情况下都可以使用 Unique 唯一索引 表示唯一的,不允许重复的索引,如果该字段信息保证不会重复例如身份证号用作索引时,可设置为unique 约束唯一标识 ...

  9. LG1879 「USACO2006NOV」Corn Fields 状压DP

    问题描述 LG1879 题解 设\(opt[i][j]\)代表前\(i\)行,且第\(i\)行状态为\(j\)的方案数. 枚举\(j\),再枚举\(k\),\(k\)为上一行的状态. 判断\(j,k\ ...

  10. R-长尾词练习

    一. 长尾关键词的特征 长尾关键词通常比较长,往往是2-3个词组成,甚至是短语,存在于内容页面,除了内容页的标题,还存在于内容中. 长尾关键词搜索量虽然非常少,而且不稳定.但是搜索量甚至超越热门目标关 ...