非对称加密常常用在登录的时候, 使用公钥对密码加密, 后台使用私钥解密。 所有客户端(iOS、Android、IE)使用同一个公钥加密, 密文只能使用后台的私钥解密。 所以RSA是很安全的一种加密方式。
RSA算法提供了生成公钥和私钥的方法, 注意是成对生成的! 一般将公钥保存在客户端、私钥保存在服务端。 黑客反编译可能拿到公钥, 但是因为私钥存储在服务器, 所以不用太担心泄密。 RSA加密算法有个特点: 每次用明文和公钥得到的加密串是不同的, 但是使用私钥都能解析出同一个明文。 这点很厉害! 想想AES、MD5等等加密方式, 使用明文得到的加密串是相同的。
注意: Android端使用“RSA/ECB/PKCS1Padding”初始化Cipher对象, Java后台使用“RSA”参数初始化Cipher对象。
private static String RSA_ANDROID = "RSA/ECB/PKCS1Padding"; private static String RSA_JAVA = "RSA";Android端使用公钥加密时:
Cipher cipher = Cipher.getInstance(RSA_ANDROID);
Java后台使用私钥解密时:
Cipher cipher = Cipher.getInstance(RSA_JAVA);
附RSA的Java后台代码实现:
<span style="font-size:18px;">package com.example;
/**
* Created by brycegao on 2016/9/19.
*/
import java.math.BigInteger;
import java.security.Key;
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.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class RSAUtils {
public static void main(String[] args) throws Exception {
//生成公私钥
//generateKeyStr();
//明文
String ming = "31231";
for (int i = 0; i < 155; i++) {
ming = ming + "fdsafdsafdsfdsafdsafdsaffdsafdsafdsaffdsafdsafdsaffdsafdsafdsaffdsafdsafdsaffdsafdsafdsaffdsafdsafdsaffdsafdsafdsaffdsafdsafdsafaf" + i;
}
//加密后的密文
String mi = encrypt(ming);
System.err.println(mi);
//解密后的明文
//RSACoder.decryptByPrivateKey(mi.getBytes());
ming = decrypt(mi);
System.err.println(ming);
}
public static void generateKeyStr() throws Exception{
HashMap<String, Object> map = RSAUtils.getKeys();
//生成公钥和私钥
RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");
String publicKeyStr = getKeyString(publicKey);
String privateKeyStr = getKeyString(privateKey);
//System.out.println("publicKey:------------");
//System.out.println(publicKeyStr);
//System.out.println("privateKey:-----------");
//System.out.println(privateKeyStr);
}
/**
* 生成公钥和私钥
* @throws NoSuchAlgorithmException
*
*/
public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{
HashMap<String, Object> map = new HashMap<String, Object>();
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;
}
/**
* 得到公钥
*
* @param key
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes = (new BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}
/**
* 得到公钥
*
* @param key
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
//X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}
/**
* 使用模和指数生成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;
}
}
/**
* 得到密钥字符串(经过base64编码)
*
* @return
*/
public static String getKeyString(Key key) throws Exception {
byte[] keyBytes = key.getEncoded();
String s = (new BASE64Encoder()).encode(keyBytes);
return s;
}
/**
* 使用模和指数生成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);
byte[] by = data.getBytes();
byte[] cipherText = cipher.doFinal(by);
return Base64.encode(cipherText);
}
public static byte[] decryptByPrivateKey2(byte[] data, RSAPrivateKey privateKey)
throws Exception {
//RSA/ECB/PKCS1Padding
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(data);
return cipherText;
}
public static String decryptByPrivateKey(byte[] data, RSAPrivateKey privateKey)
throws Exception {
//RSA/ECB/PKCS1Padding
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(data);
String ming =new String(cipherText);
return ming;
}
/**
* 私钥解密
*
* @param data
* @param privateKey
* @return
* @throws Exception
*/
public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)
throws Exception {
//RSA/ECB/PKCS1Padding
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] by = Base64.decode(data);
byte[] cipherText = cipher.doFinal(by);
String ming =new String(cipherText);
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<x+z; 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<x+z; 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;
}
public static String DefaultPubKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCapIG/XijKqbesb0LC9CdmcKbnzPJMIsa6tRbIwi1FKm3GSYkzYoJWQmHYq5WxVxDosc5aj2b0wBvhQ4WwLgaaNjyC5hcIfhSwAqMFD/bqi48LA4wBrTD62sxNFBzwiOb+q/8AYQPgD6jA/mrqUvUZSNrS3TI7x9zO1FGQi7nZ1wIDAQAB";
public static String DefaultPriKey ="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJqkgb9eKMqpt6xvQsL0J2ZwpufM8kwixrq1FsjCLUUqbcZJiTNiglZCYdirlbFXEOixzlqPZvTAG+FDhbAuBpo2PILmFwh+FLACowUP9uqLjwsDjAGtMPrazE0UHPCI5v6r/wBhA+APqMD+aupS9RlI2tLdMjvH3M7UUZCLudnXAgMBAAECgYB13Pg/AOcaP+yL8mjx6eC1xRqRBbWOrdrFpwvsi4KxerscLCP0FBq+3+1vlKeM+I0crZhXkYCo/lrBgBM+ynWgmHU5XjV+rBl+hHEEOsylUW6ari6r/3rae7RzVxjEzYoHb0ZKN5Hs6odVFXeblLUWNUicPTkzusXzoYTocrPdgQJBAMd2Ykc243FKOPSaCYRtbmH0OOEWPqkrOaPzMjQKFNKMbaYu+4E/+njHUptbbOWlsrktJIVvsmPW/BDsapDUCeECQQDGedswNZ32yGGPdQbsfVu9lokg2AJu6GCx7aQg4qwea5jwgPOCyNMgWG2ns/CJItvNPLxoMaT+qN84U8OcRAq3AkEAgskhD8jxwWsFhX0rGGYYpqnYUd6gH5R0KwhftreVh6kEjJ7p0on81gz8IVoFQV8wnTL4a3Yd5lEk3oPmLCicgQJARBX1XTpncAsZfK72qxXt7MHBVOUFIKrS0PbmwOlBhkX+9zIlVw4xbv0m0MrnjwPIR0W4lD3DjiC8QoRprCejTQJBAMTOGWYGaoJ9WlQUI2aoPpkPsDy7vfL2z0PxFl3ZkETLdmT9knSMQX4biZD4irXWicy9w1wD5vxYaAKyYofkLFE=";
public static String encrypt(String plaintext) throws Exception{
RSAPublicKey pubKey = RSAUtils.getPublicKey(DefaultPubKey);
//加密后的密文
return RSAUtils.encryptByPublicKey(plaintext, pubKey);
}
public static byte[] decrypt(byte[] mi)throws Exception{
RSAPrivateKey priKey = RSAUtils.getPrivateKey(DefaultPriKey);
//解密后的明文
return RSAUtils.decryptByPrivateKey2(mi, priKey);
}
public static String decrypt(String mi)throws Exception{
RSAPrivateKey priKey = RSAUtils.getPrivateKey(DefaultPriKey);
//解密后的明文
return RSAUtils.decryptByPrivateKey(mi, priKey);
}
}
</span>