这个RSA加密其实自己也没有完全弄清楚,只是在网上自己找了一些资料,也是为了记录自己的代码。

概述

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;
  }
 }

其中KeyPair是android自带的类,可以自带生成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(1024);
 }

/**
  * 随机生成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(0) == '-')
   {
    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', '0', '1', '2', '3', '4', '5',
   '6', '7', '8', '9', '+', '/' };
 private static byte[] base64DecodeChars = new byte[]
 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,
   54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
   12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
   30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
   -1, -1, -1 };

/**
  * 加密
  *
  * @param data
  * @return
  */
 public static String encode(byte[] data)
 {
  StringBuffer sb = new StringBuffer();
  int len = data.length;
  int i = 0;
  int b1, b2, b3;
  while (i < len)
  {
   b1 = data[i++] & 0xff;
   if (i == len)
   {
    sb.append(base64EncodeChars[b1 >>> 2]);
    sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
    sb.append("==");
    break;
   }
   b2 = data[i++] & 0xff;
   if (i == len)
   {
    sb.append(base64EncodeChars[b1 >>> 2]);
    sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
    sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
    sb.append("=");
    break;
   }
   b3 = data[i++] & 0xff;
   sb.append(base64EncodeChars[b1 >>> 2]);
   sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
   sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
   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 = 0;
  int b1, b2, b3, b4;
  while (i < len)
  {

do
   {
    b1 = base64DecodeChars[data[i++]];
   } while (i < len && b1 == -1);
   if (b1 == -1)
    break;

do
   {
    b2 = base64DecodeChars[data[i++]];
   } while (i < len && b2 == -1);
   if (b2 == -1)
    break;
   sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));

do
   {
    b3 = data[i++];
    if (b3 == 61)
     return sb.toString().getBytes("iso8859-1");
    b3 = base64DecodeChars[b3];
   } while (i < len && b3 == -1);
   if (b3 == -1)
    break;
   sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));

do
   {
    b4 = data[i++];
    if (b4 == 61)
     return sb.toString().getBytes("iso8859-1");
    b4 = base64DecodeChars[b4];
   } while (i < len && b4 == -1);
   if (b4 == -1)
    break;
   sb.append((char) (((b3 & 0x03) << 6) | b4));
  }
  return sb.toString().getBytes("iso8859-1");
 }

}

最后直接使用和加密就可以了,文章参考了别人的博客,如果看不懂,那建议去网上再搜索一下。

android RSA加密相关推荐

  1. Android RSA 加密

    没想到被Android里的RSA加密折腾了几个小时,主要还是自己对RSA加密的原理不了解,然后网上相关的资料也少. 使用AndroidUtilCode工具类中的EncryptUtils.encrypt ...

  2. Android RSA加密解密

    转载: http://blog.csdn.net/bbld_/article/details/38777491 概述 RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事实:将两个大素 ...

  3. Android RSA加密解密的 工具类的使用

    RSA 比较特殊,我们首先要生成私钥和公钥,然后在加密的时候,使用私钥加密,在解密的时候使用公钥解密. //RSA 的初始化,获得私钥和密钥public void rsaInit(){try {Key ...

  4. android rsa加密工具类,GitHub - Lerist/encrypt: Android 加密解密工具包。

    Encrypt(加密工具) 字符串,byte[],文件等对象的加密和解密工具集合,包含了多种加密方案. 加密类型 摘要 相关方法 简单加密 换一种编码格式 Base64Util 单向加密 只能加密,不 ...

  5. Android RSA加密解密,用于和服务器交互时的请求

    概述 RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对其乘积进行因式分解却极其困 难,因此可以将乘积公开作为加密密钥,即公钥,而两个大素数 ...

  6. java android rsa加密解密_Android RSA加密解密

    转载 http://blog.csdn.net/bbld_/article/details/38777491 RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事实:将两个大素数相乘十 ...

  7. Android RSA加密与SHA256算法工具类

    Android开发中我们经常会用到各种加密,一般针对一些密码加密,下面给说一下RSA加密与SHA256算法的使用方法: 附加RSA加密jar包:点击打开链接 public class RsaHelpe ...

  8. android rsa加密工具类,android RSA加密

    释放双眼,带上耳机,听听看~! 这个RSA加密其实自己也没有完全弄清楚,只是在网上自己找了一些资料,也是为了记录自己的代码. 概述 RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事 ...

  9. ios android rsa加密解密,IOS RSA加密解密

    最近项目中对接口进行了rsa 加密. 写下过程以便复习 公钥私钥一般是有后台给的,这里为了方便 自己生成一对秘钥 生成公钥 私钥. 终端中: 生成原始 RSA私钥文件 private_key.pem ...

最新文章

  1. linux下的vi与vim
  2. linux 删除文件夹
  3. linux存储--虚拟内存详解MMU、页表(十)
  4. [云炬小程序实战笔记] 第1章 全新版:初识微信小程序
  5. Machine Schedule为什么UVA过了POJ过不了
  6. Cortex M3存储器映射
  7. Web高效管理多个项目的SVN仓库
  8. 半小时让你成为EXCEL高手
  9. 从命令行接收多个数字,求和之后输出结果
  10. pytorch制作test和train下面还有类别的文件(从一个图片文件中复制)
  11. CMOS数字集成电路
  12. 企业为什么需要BI决策系统?
  13. 计算机管理及维护培训考试题,计算机考试题库和答案_浅析高校公共计算机机房管理与维护...
  14. sd和sem啥区别_标准差SD和标准误sem的区别
  15. gearman和python客户端的安装和使用
  16. 脏写、脏读、不可重复读、幻读
  17. 欧氏距离 VS 余弦距离
  18. RabbitMQ(四):mandatory、immediate、备份交换器
  19. 数据库-Mysql-Ⅰ
  20. com.itextpdf.io.IOException Type of font null is not recognized

热门文章

  1. windows下安装及配置 golang 的Web框架Beego环境
  2. 实验四 恶意代码技术
  3. linux驱动(七)gpiolib库详解
  4. Java 对象引用以及对象赋值
  5. iOS: 讯飞语音的使用
  6. Linux下恢复误删文件:思路+实践
  7. CSS控制表格的方法
  8. lamp兄弟连视频笔记
  9. 共享上网 路由器设置图解
  10. WebDriver高级应用实例(7)