概述

RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对其乘积进行因式分解却极其困 难,因此可以将乘积公开作为加密密钥,即公钥,而两个大素数组合成私钥。公钥是可发布的供任何人使用,私钥则为自己所有,供解密之用。关于RSA其它需要了解的知识,参考维基百科:http://zh.wikipedia.org/zh-cn/RSA%E5%8A%A0%E5%AF%86%E6%BC%94%E7%AE%97%E6%B3%95

在项目开发中对于一些比较敏感的信息需要对其进行加密处理,我们就可以使用RSA这种非对称加密算法来对数据进行加密处理。

使用

秘钥对的生成

1、我们可以在代码里随机生成密钥对

    /**
* 随机生成RSA密钥对
*
* @param keyLength
* 密钥长度,范围:512~2048<br>
* 一般1024
* @return
*/
public static KeyPair generateRSAKeyPair(int keyLength)
{
try
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return null;
}
}

2、下载开源RSA密钥生成工具openssl(通常Linux系统都自带该程序),解压缩至独立的文件夹,进入其中的bin目录,执行以下命令:

openssl genrsa -out rsa_private_key.pem
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

第一条命令生成原始 RSA私钥文件 rsa_private_key.pem,第二条命令将原始 RSA私钥转换为 pkcs8格式,第三条生成RSA公钥 rsa_public_key.pem
从上面看出通过私钥能生成对应的公钥,因此我们将私钥private_key.pem用在服务器端,公钥发放给android跟ios等前端

代码中的使用

首先我们需要封装写个RSA的工具类,方便加密解密的操作。

package com.example.rsa;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; /**
* @author Mr.Zheng
* @date 2014年8月22日 下午1:44:23
*/
public final class RSAUtils
{
private static String RSA = "RSA"; /**
* 随机生成RSA密钥对(默认密钥长度为1024)
*
* @return
*/
public static KeyPair generateRSAKeyPair()
{
return generateRSAKeyPair();
} /**
* 随机生成RSA密钥对
*
* @param keyLength
* 密钥长度,范围:512~2048<br>
* 一般1024
* @return
*/
public static KeyPair generateRSAKeyPair(int keyLength)
{
try
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return null;
}
} /**
* 用公钥加密 <br>
* 每次加密的字节数,不能超过密钥的长度值减去11
*
* @param data
* 需加密数据的byte数据
* @param pubKey
* 公钥
* @return 加密后的byte型数据
*/
public static byte[] encryptData(byte[] data, PublicKey publicKey)
{
try
{
Cipher cipher = Cipher.getInstance(RSA);
// 编码前设定编码方式及密钥
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 传入编码数据并返回编码结果
return cipher.doFinal(data);
} catch (Exception e)
{
e.printStackTrace();
return null;
}
} /**
* 用私钥解密
*
* @param encryptedData
* 经过encryptedData()加密返回的byte数据
* @param privateKey
* 私钥
* @return
*/
public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)
{
try
{
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedData);
} catch (Exception e)
{
return null;
}
} /**
* 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException
{
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} /**
* 通过私钥byte[]将公钥还原,适用于RSA算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException
{
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
} /**
* 使用N、e值还原公钥
*
* @param modulus
* @param publicExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getPublicKey(String modulus, String publicExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} /**
* 使用N、d值还原私钥
*
* @param modulus
* @param privateExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(String modulus, String privateExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
} /**
* 从字符串中加载公钥
*
* @param publicKeyStr
* 公钥数据字符串
* @throws Exception
* 加载公钥时产生的异常
*/
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception
{
try
{
byte[] buffer = Base64Utils.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) 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指令)。
*
* @param privateKeyStr
* @return
* @throws Exception
*/
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception
{
try
{
byte[] buffer = Base64Utils.decode(privateKeyStr);
// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e)
{
throw new Exception("无此算法");
} catch (InvalidKeySpecException e)
{
throw new Exception("私钥非法");
} catch (NullPointerException e)
{
throw new Exception("私钥数据为空");
}
} /**
* 从文件中输入流中加载公钥
*
* @param in
* 公钥输入流
* @throws Exception
* 加载公钥时产生的异常
*/
public static PublicKey loadPublicKey(InputStream in) throws Exception
{
try
{
return loadPublicKey(readKey(in));
} catch (IOException e)
{
throw new Exception("公钥数据流读取错误");
} catch (NullPointerException e)
{
throw new Exception("公钥输入流为空");
}
} /**
* 从文件中加载私钥
*
* @param keyFileName
* 私钥文件名
* @return 是否成功
* @throws Exception
*/
public static PrivateKey loadPrivateKey(InputStream in) throws Exception
{
try
{
return loadPrivateKey(readKey(in));
} catch (IOException e)
{
throw new Exception("私钥数据读取错误");
} catch (NullPointerException e)
{
throw new Exception("私钥输入流为空");
}
} /**
* 读取密钥信息
*
* @param in
* @return
* @throws IOException
*/
private static String readKey(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() == '-')
{
continue;
} else
{
sb.append(readLine);
sb.append('\r');
}
} return sb.toString();
} /**
* 打印公钥信息
*
* @param publicKey
*/
public static void printPublicKeyInfo(PublicKey publicKey)
{
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
System.out.println("----------RSAPublicKey----------");
System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
} public static void printPrivateKeyInfo(PrivateKey privateKey)
{
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
System.out.println("----------RSAPrivateKey ----------");
System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString()); } }

上面需要注意的就是加密是有长度限制的,过长的话会抛异常!!!

代码中有些需要使用Base64再转换的,而java中不自带,Android中自带,所以自己写出一个来,方便Java后台使用

package com.example.rsa;

import java.io.UnsupportedEncodingException;

/**
* @author Mr.Zheng
* @date 2014年8月22日 下午9:50:28
*/
public class Base64Utils
{
private static char[] base64EncodeChars = new char[]
{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '', '', '', '', '', '',
'', '', '', '', '+', '/' };
private static byte[] base64DecodeChars = new byte[]
{ -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -,
-, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, , -, -, -, , , ,
, , , , , , , , -, -, -, -, -, -, -, , , , , , , , , , , , ,
, , , , , , , , , , , , , , -, -, -, -, -, -, , , , ,
, , , , , , , , , , , , , , , , , , , , , , -, -,
-, -, - }; /**
* 加密
*
* @param data
* @return
*/
public static String encode(byte[] data)
{
StringBuffer sb = new StringBuffer();
int len = data.length;
int i = ;
int b1, b2, b3;
while (i < len)
{
b1 = data[i++] & 0xff;
if (i == len)
{
sb.append(base64EncodeChars[b1 >>> ]);
sb.append(base64EncodeChars[(b1 & 0x3) << ]);
sb.append("==");
break;
}
b2 = data[i++] & 0xff;
if (i == len)
{
sb.append(base64EncodeChars[b1 >>> ]);
sb.append(base64EncodeChars[((b1 & 0x03) << ) | ((b2 & 0xf0) >>> )]);
sb.append(base64EncodeChars[(b2 & 0x0f) << ]);
sb.append("=");
break;
}
b3 = data[i++] & 0xff;
sb.append(base64EncodeChars[b1 >>> ]);
sb.append(base64EncodeChars[((b1 & 0x03) << ) | ((b2 & 0xf0) >>> )]);
sb.append(base64EncodeChars[((b2 & 0x0f) << ) | ((b3 & 0xc0) >>> )]);
sb.append(base64EncodeChars[b3 & 0x3f]);
}
return sb.toString();
} /**
* 解密
*
* @param str
* @return
*/
public static byte[] decode(String str)
{
try
{
return decodePrivate(str);
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return new byte[]
{};
} private static byte[] decodePrivate(String str) throws UnsupportedEncodingException
{
StringBuffer sb = new StringBuffer();
byte[] data = null;
data = str.getBytes("US-ASCII");
int len = data.length;
int i = ;
int b1, b2, b3, b4;
while (i < len)
{ do
{
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -);
if (b1 == -)
break; do
{
b2 = base64DecodeChars[data[i++]];
} while (i < len && b2 == -);
if (b2 == -)
break;
sb.append((char) ((b1 << ) | ((b2 & 0x30) >>> ))); do
{
b3 = data[i++];
if (b3 == )
return sb.toString().getBytes("iso8859-1");
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -);
if (b3 == -)
break;
sb.append((char) (((b2 & 0x0f) << ) | ((b3 & 0x3c) >>> ))); do
{
b4 = data[i++];
if (b4 == )
return sb.toString().getBytes("iso8859-1");
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -);
if (b4 == -)
break;
sb.append((char) (((b3 & 0x03) << ) | b4));
}
return sb.toString().getBytes("iso8859-1");
} }

最后就是真正使用它们了:

package com.example.rsa;

import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey; import android.app.Activity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText; public class MainActivity extends Activity implements OnClickListener
{
private Button btn1, btn2;// 加密,解密
private EditText et1, et2, et3;// 需加密的内容,加密后的内容,解密后的内容 /* 密钥内容 base64 code */
private static String PUCLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfRTdcPIH10gT9f31rQuIInLwe"
+ "\r" + "7fl2dtEJ93gTmjE9c2H+kLVENWgECiJVQ5sonQNfwToMKdO0b3Olf4pgBKeLThra" + "\r"
+ "z/L3nYJYlbqjHC3jTjUnZc0luumpXGsox62+PuSGBlfb8zJO6hix4GV/vhyQVCpG" + "\r"
+ "9aYqgE7zyTRZYX9byQIDAQAB" + "\r";
private static String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ9FN1w8gfXSBP1/"
+ "\r" + "fWtC4gicvB7t+XZ20Qn3eBOaMT1zYf6QtUQ1aAQKIlVDmyidA1/BOgwp07Rvc6V/" + "\r"
+ "imAEp4tOGtrP8vedgliVuqMcLeNONSdlzSW66alcayjHrb4+5IYGV9vzMk7qGLHg" + "\r"
+ "ZX++HJBUKkb1piqATvPJNFlhf1vJAgMBAAECgYA736xhG0oL3EkN9yhx8zG/5RP/" + "\r"
+ "WJzoQOByq7pTPCr4m/Ch30qVerJAmoKvpPumN+h1zdEBk5PHiAJkm96sG/PTndEf" + "\r"
+ "kZrAJ2hwSBqptcABYk6ED70gRTQ1S53tyQXIOSjRBcugY/21qeswS3nMyq3xDEPK" + "\r"
+ "XpdyKPeaTyuK86AEkQJBAM1M7p1lfzEKjNw17SDMLnca/8pBcA0EEcyvtaQpRvaL" + "\r"
+ "n61eQQnnPdpvHamkRBcOvgCAkfwa1uboru0QdXii/gUCQQDGmkP+KJPX9JVCrbRt" + "\r"
+ "7wKyIemyNM+J6y1ZBZ2bVCf9jacCQaSkIWnIR1S9UM+1CFE30So2CA0CfCDmQy+y" + "\r"
+ "7A31AkB8cGFB7j+GTkrLP7SX6KtRboAU7E0q1oijdO24r3xf/Imw4Cy0AAIx4KAu" + "\r"
+ "L29GOp1YWJYkJXCVTfyZnRxXHxSxAkEAvO0zkSv4uI8rDmtAIPQllF8+eRBT/deD" + "\r"
+ "JBR7ga/k+wctwK/Bd4Fxp9xzeETP0l8/I+IOTagK+Dos8d8oGQUFoQJBAI4Nwpfo" + "\r"
+ "MFaLJXGY9ok45wXrcqkJgM+SN6i8hQeujXESVHYatAIL/1DgLi+u46EFD69fw0w+" + "\r" + "c7o0HLlMsYPAzJw="
+ "\r"; @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
} private void initView()
{
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this); et1 = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
et3 = (EditText) findViewById(R.id.et3);
} @Override
public void onClick(View v)
{
switch (v.getId())
{
// 加密
case R.id.btn1:
String source = et1.getText().toString().trim();
try
{
// 从字符串中得到公钥
// PublicKey publicKey = RSAUtils.loadPublicKey(PUCLIC_KEY);
// 从文件中得到公钥
InputStream inPublic = getResources().getAssets().open("rsa_public_key.pem");
PublicKey publicKey = RSAUtils.loadPublicKey(inPublic);
// 加密
byte[] encryptByte = RSAUtils.encryptData(source.getBytes(), publicKey);
// 为了方便观察吧加密后的数据用base64加密转一下,要不然看起来是乱码,所以解密是也是要用Base64先转换
String afterencrypt = Base64Utils.encode(encryptByte);
et2.setText(afterencrypt);
} catch (Exception e)
{
e.printStackTrace();
}
break;
// 解密
case R.id.btn2:
String encryptContent = et2.getText().toString().trim();
try
{
// 从字符串中得到私钥
// PrivateKey privateKey = RSAUtils.loadPrivateKey(PRIVATE_KEY);
// 从文件中得到私钥
InputStream inPrivate = getResources().getAssets().open("pkcs8_rsa_private_key.pem");
PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);
// 因为RSA加密后的内容经Base64再加密转换了一下,所以先Base64解密回来再给RSA解密
byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(encryptContent), privateKey);
String decryptStr = new String(decryptByte);
et3.setText(decryptStr);
} catch (Exception e)
{
e.printStackTrace();
}
break;
default:
break;
}
} }

我把密钥放到assest资源文件夹里了,也可以直接使用字符串得到,上面注释掉了。

后记:后来发现,android的rsa机制和php,java的默认机制有点不同

也就是说android系统的RSA实现是"RSA/None/NoPadding",而标准JDK实现是"RSA/ECB/PKCS1Padding"

具体解决方法http://stackoverflow.com/questions/13556295/rsa-encryption-in-android

稍微作修改一下这里:Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");就行了

修改后的RSAUtils类

package com.example.rsa;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; /**
* @author Mr.Zheng
* @date 2014年8月22日 下午1:44:23
*/
public final class RSAUtils
{
private static String RSA = "RSA";
private static String RSA1 = "RSA/ECB/PKCS1Padding";
/**
* 随机生成RSA密钥对(默认密钥长度为1024)
*
* @return
*/
public static KeyPair generateRSAKeyPair()
{
return generateRSAKeyPair();
} /**
* 随机生成RSA密钥对
*
* @param keyLength
* 密钥长度,范围:512~2048<br>
* 一般1024
* @return
*/
public static KeyPair generateRSAKeyPair(int keyLength)
{
try
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return null;
}
} /**
* 用公钥加密 <br>
* 每次加密的字节数,不能超过密钥的长度值减去11
*
* @param data
* 需加密数据的byte数据
* @param pubKey
* 公钥
* @return 加密后的byte型数据
*/
public static byte[] encryptData(byte[] data, PublicKey publicKey)
{
try
{
Cipher cipher = Cipher.getInstance(RSA1);
// 编码前设定编码方式及密钥
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 传入编码数据并返回编码结果
return cipher.doFinal(data);
} catch (Exception e)
{
e.printStackTrace();
return null;
}
} /**
* 用私钥解密
*
* @param encryptedData
* 经过encryptedData()加密返回的byte数据
* @param privateKey
* 私钥
* @return
*/
public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)
{
try
{
Cipher cipher = Cipher.getInstance(RSA1);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedData);
} catch (Exception e)
{
return null;
}
} /**
* 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException
{
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} /**
* 通过私钥byte[]将公钥还原,适用于RSA算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException
{
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
} /**
* 使用N、e值还原公钥
*
* @param modulus
* @param publicExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getPublicKey(String modulus, String publicExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} /**
* 使用N、d值还原私钥
*
* @param modulus
* @param privateExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(String modulus, String privateExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
} /**
* 从字符串中加载公钥
*
* @param publicKeyStr
* 公钥数据字符串
* @throws Exception
* 加载公钥时产生的异常
*/
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception
{
try
{
byte[] buffer = Base64Utils.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) 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指令)。
*
* @param privateKeyStr
* @return
* @throws Exception
*/
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception
{
try
{
byte[] buffer = Base64Utils.decode(privateKeyStr);
// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e)
{
throw new Exception("无此算法");
} catch (InvalidKeySpecException e)
{
throw new Exception("私钥非法");
} catch (NullPointerException e)
{
throw new Exception("私钥数据为空");
}
} /**
* 从文件中输入流中加载公钥
*
* @param in
* 公钥输入流
* @throws Exception
* 加载公钥时产生的异常
*/
public static PublicKey loadPublicKey(InputStream in) throws Exception
{
try
{
return loadPublicKey(readKey(in));
} catch (IOException e)
{
throw new Exception("公钥数据流读取错误");
} catch (NullPointerException e)
{
throw new Exception("公钥输入流为空");
}
} /**
* 从文件中加载私钥
*
* @param keyFileName
* 私钥文件名
* @return 是否成功
* @throws Exception
*/
public static PrivateKey loadPrivateKey(InputStream in) throws Exception
{
try
{
return loadPrivateKey(readKey(in));
} catch (IOException e)
{
throw new Exception("私钥数据读取错误");
} catch (NullPointerException e)
{
throw new Exception("私钥输入流为空");
}
} /**
* 读取密钥信息
*
* @param in
* @return
* @throws IOException
*/
private static String readKey(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() == '-')
{
continue;
} else
{
sb.append(readLine);
sb.append('\r');
}
} return sb.toString();
} /**
* 打印公钥信息
*
* @param publicKey
*/
public static void printPublicKeyInfo(PublicKey publicKey)
{
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
System.out.println("----------RSAPublicKey----------");
System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
} public static void printPrivateKeyInfo(PrivateKey privateKey)
{
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
System.out.println("----------RSAPrivateKey ----------");
System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString()); } }

Android RSA加密解密的更多相关文章

  1. android -------- RSA加密解密算法

    RSA加密算法是一种非对称加密算法.在公开密钥加密和电子商业中RSA被广泛使用 RSA公开密钥密码体制.所谓的公开密钥密码体制就是使用不同的加密密钥与解密密钥,是一种“由已知加密密钥推导出解密密钥在计 ...

  2. 兼容javascript和C#的RSA加密解密算法,对web提交的数据进行加密传输

    Web应用中往往涉及到敏感的数据,由于HTTP协议以明文的形式与服务器进行交互,因此可以通过截获请求的数据包进行分析来盗取有用的信息.虽然https可以对传输的数据进行加密,但是必须要申请证书(一般都 ...

  3. iOS使用Security.framework进行RSA 加密解密签名和验证签名

    iOS 上 Security.framework为我们提供了安全方面相关的api: Security框架提供的RSA在iOS上使用的一些小结 支持的RSA keySize 大小有:512,768,10 ...

  4. openssl evp RSA 加密解密

    openssl evp RSA 加密解密 可以直接使用RSA.h 提供的接口 如下测试使用EVP提供的RSA接口 1. EVP提供的RSA 加密解密 主要接口: int EVP_PKEY_encryp ...

  5. C# 与JAVA 的RSA 加密解密交互,互通,C#使用BouncyCastle来实现私钥加密,公钥解密的方法

    因为C#的RSA加密解密只有公钥加密,私钥解密,没有私钥加密,公钥解密.在网上查了很久也没有很好的实现.BouncyCastle的文档少之又少.很多人可能会说,C#也是可以的,通过Biginteger ...

  6. Cryptopp iOS 使用 RSA加密解密和签名验证签名

    Cryptopp 是一个c++写的功能完善的密码学工具,类似于openssl 官网:https://www.cryptopp.com 以下主要演示Cryptopp 在iOS上的RSA加密解密签名与验证 ...

  7. C# Java间进行RSA加密解密交互

    原文:C# Java间进行RSA加密解密交互 这里,讲一下RSA算法加解密在C#和Java之间交互的问题,这两天纠结了很久,也看了很多其他人写的文章,颇受裨益,但没能解决我的实际问题,终于,还是被我捣 ...

  8. C# Java间进行RSA加密解密交互(二)

    原文:C# Java间进行RSA加密解密交互(二) 接着前面一篇文章C# Java间进行RSA加密解密交互,继续探讨这个问题. 在前面,虽然已经实现了C# Java间进行RSA加密解密交互,但是还是与 ...

  9. C# Java间进行RSA加密解密交互(三)

    原文:C# Java间进行RSA加密解密交互(三) 接着前面一篇C# Java间进行RSA加密解密交互(二)说吧,在上篇中为了实现 /** * RSA加密 * @param text--待加密的明文 ...

随机推荐

  1. iOS开发实用干货——强化你的Xcode控制台

    f(x) 郑秀晶程序员不要整天看代码,偶尔也要看看风景?? www.90168.org先上一张我的Xcode控制台的图片让你们感受一下 酷炫控制台 是不是觉得很酷?不过仅仅是酷还是远远不够的,当你点击 ...

  2. 使用sqoop 在关系型数据库和Hadoop之间实现数据的抽取

    (一)从关系型数据库导入至HDFS 1.将下面的参数保持为 import.script import --connectjdbc:mysql://192.168.1.14:3306/test--use ...

  3. section和article元素

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. 每天一个linux命令--locate

    linux下,不知道自己安装的程序放在哪里了,可以使用locate命令进行查找. [hongye@dev107 ~]$ locate activemq.xml /home/hongye/hongyeC ...

  5. ACM: Long Live the Queen - 树上的DP

    Long Live the Queen Time Limit:250MS     Memory Limit:4096KB     64bit IO Format:%I64d & %I64u D ...

  6. HttpClient_使用httpclient必须知道的参数设置及代码写法、存在的风险

    结论: 如果使用httpclient 3.1并发量比较大的项目,最好升级到httpclient4.2.3上,保证并发量大时能抗住.httpclient 4.3.3,目前还有一些bug:还是用4.2.x ...

  7. 关于window的resize事件

    也许你也遇到过这样的问题,或者还没注意到有过这样的问题,如下代码,在窗口发生变化时,会进入死循环: var _funResize = function(){ console.log('resize.. ...

  8. docker 报错Failed to start Docker Storage Setup. 的处理基本都是容器满了

    :: localhost docker-storage-setup: Volume group extents): required. Apr :: localhost systemd: docker ...

  9. CentOS默认开放的本地端口范围

    系统本地开放端口的范围:(默认30000多到60000多) [root@linux2 ~]# vim /etc/sysctl.conf net.ipv4.ip_local_port_range = 1 ...

  10. php链接mysql数据库

    php连接数据库有三种方法,刚刚发现通过mysql_connect,mysql_query连接已被废弃,而现在推荐的是通过“面向对象方法”和“PDO方法”连接数据库. 而我在使用面向对象的方法连接时, ...