/** * 随机生成RSA密钥对 * * @param keyLength 密钥长度,范围:512~2048 * 一般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;}}具体加密实现:
/** * 用公钥对字符串进行加密 * * @param data 原文 */public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {// 得到公钥X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);KeyFactory kf = KeyFactory.getInstance(RSA);PublicKey keyPublic = kf.generatePublic(keySpec);// 加密数据Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);cp.init(Cipher.ENCRYPT_MODE, keyPublic);return cp.doFinal(data);}私钥加密
/** * 私钥加密 * * @param data待加密数据 * @param privateKey 密钥 * @return byte[] 加密数据 */public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception {// 得到私钥PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);KeyFactory kf = KeyFactory.getInstance(RSA);PrivateKey keyPrivate = kf.generatePrivate(keySpec);// 数据加密Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);cipher.init(Cipher.ENCRYPT_MODE, keyPrivate);return cipher.doFinal(data);}公钥解密
/** * 公钥解密 * * @param data 待解密数据 * @param publicKey 密钥 * @return byte[] 解密数据 */public static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {// 得到公钥X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);KeyFactory kf = KeyFactory.getInstance(RSA);PublicKey keyPublic = kf.generatePublic(keySpec);// 数据解密Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);cipher.init(Cipher.DECRYPT_MODE, keyPublic);return cipher.doFinal(data);}私钥解密
/** * 使用私钥进行解密 */public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {// 得到私钥PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);KeyFactory kf = KeyFactory.getInstance(RSA);PrivateKey keyPrivate = kf.generatePrivate(keySpec);// 解密数据Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);cp.init(Cipher.DECRYPT_MODE, keyPrivate);byte[] arr = cp.doFinal(encrypted);return arr;}几个全局变量解说:
public static final String RSA = "RSA";// 非对称加密密钥算法public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式public static final int DEFAULT_KEY_SIZE = 2048;//秘钥默认长度public static final byte[] DEFAULT_SPLIT = "#PART#".getBytes();// 当要加密的内容超过bufferSize,则采用partSplit进行分块加密public static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11;// 当前秘钥支持加密的最大字节数加密填充方式
/** * 用公钥对字符串进行分段加密 * */public static byte[] encryptByPublicKeyForSpilt(byte[] data, byte[] publicKey) throws Exception {int dataLen = data.length;if (dataLen <= DEFAULT_BUFFERSIZE) {return encryptByPublicKey(data, publicKey);}List<Byte> allBytes = new ArrayList<Byte>(2048);int bufIndex = 0;int subDataLoop = 0;byte[] buf = new byte[DEFAULT_BUFFERSIZE];for (int i = 0; i < dataLen; i++) {buf[bufIndex] = data[i];if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {subDataLoop++;if (subDataLoop != 1) {for (byte b : DEFAULT_SPLIT) {allBytes.add(b);}}byte[] encryptBytes = encryptByPublicKey(buf, publicKey);for (byte b : encryptBytes) {allBytes.add(b);}bufIndex = 0;if (i == dataLen - 1) {buf = null;} else {buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];}}}byte[] bytes = new byte[allBytes.size()];{int i = 0;for (Byte b : allBytes) {bytes[i++] = b.byteValue();}}return bytes;}私钥分段加密
/** * 分段加密 * * @param data要加密的原始数据 * @param privateKey 秘钥 */public static byte[] encryptByPrivateKeyForSpilt(byte[] data, byte[] privateKey) throws Exception {int dataLen = data.length;if (dataLen <= DEFAULT_BUFFERSIZE) {return encryptByPrivateKey(data, privateKey);}List<Byte> allBytes = new ArrayList<Byte>(2048);int bufIndex = 0;int subDataLoop = 0;byte[] buf = new byte[DEFAULT_BUFFERSIZE];for (int i = 0; i < dataLen; i++) {buf[bufIndex] = data[i];if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {subDataLoop++;if (subDataLoop != 1) {for (byte b : DEFAULT_SPLIT) {allBytes.add(b);}}byte[] encryptBytes = encryptByPrivateKey(buf, privateKey);for (byte b : encryptBytes) {allBytes.add(b);}bufIndex = 0;if (i == dataLen - 1) {buf = null;} else {buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];}}}byte[] bytes = new byte[allBytes.size()];{int i = 0;for (Byte b : allBytes) {bytes[i++] = b.byteValue();}}return bytes;}公钥分段解密
/** * 公钥分段解密 * * @param encrypted 待解密数据 * @param publicKey 密钥 */public static byte[] decryptByPublicKeyForSpilt(byte[] encrypted, byte[] publicKey) throws Exception {int splitLen = DEFAULT_SPLIT.length;if (splitLen <= 0) {return decryptByPublicKey(encrypted, publicKey);}int dataLen = encrypted.length;List<Byte> allBytes = new ArrayList<Byte>(1024);int latestStartIndex = 0;for (int i = 0; i < dataLen; i++) {byte bt = encrypted[i];boolean isMatchSplit = false;if (i == dataLen - 1) {// 到data的最后了byte[] part = new byte[dataLen - latestStartIndex];System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);byte[] decryptPart = decryptByPublicKey(part, publicKey);for (byte b : decryptPart) {allBytes.add(b);}latestStartIndex = i + splitLen;i = latestStartIndex - 1;} else if (bt == DEFAULT_SPLIT[0]) {// 这个是以split[0]开头if (splitLen > 1) {if (i + splitLen < dataLen) {// 没有超出data的范围for (int j = 1; j < splitLen; j++) {if (DEFAULT_SPLIT[j] != encrypted[i + j]) {break;}if (j == splitLen - 1) {// 验证到split的最后一位,都没有break,则表明已经确认是split段isMatchSplit = true;}}}} else {// split只有一位,则已经匹配了isMatchSplit = true;}}if (isMatchSplit) {byte[] part = new byte[i - latestStartIndex];System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);byte[] decryptPart = decryptByPublicKey(part, publicKey);for (byte b : decryptPart) {allBytes.add(b);}latestStartIndex = i + splitLen;i = latestStartIndex - 1;}}byte[] bytes = new byte[allBytes.size()];{int i = 0;for (Byte b : allBytes) {bytes[i++] = b.byteValue();}}return bytes;}私钥分段解密
/** * 使用私钥分段解密 * */public static byte[] decryptByPrivateKeyForSpilt(byte[] encrypted, byte[] privateKey) throws Exception {int splitLen = DEFAULT_SPLIT.length;if (splitLen <= 0) {return decryptByPrivateKey(encrypted, privateKey);}int dataLen = encrypted.length;List<Byte> allBytes = new ArrayList<Byte>(1024);int latestStartIndex = 0;for (int i = 0; i < dataLen; i++) {byte bt = encrypted[i];boolean isMatchSplit = false;if (i == dataLen - 1) {// 到data的最后了byte[] part = new byte[dataLen - latestStartIndex];System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);byte[] decryptPart = decryptByPrivateKey(part, privateKey);for (byte b : decryptPart) {allBytes.add(b);}latestStartIndex = i + splitLen;i = latestStartIndex - 1;} else if (bt == DEFAULT_SPLIT[0]) {// 这个是以split[0]开头if (splitLen > 1) {if (i + splitLen < dataLen) {// 没有超出data的范围for (int j = 1; j < splitLen; j++) {if (DEFAULT_SPLIT[j] != encrypted[i + j]) {break;}if (j == splitLen - 1) {// 验证到split的最后一位,都没有break,则表明已经确认是split段isMatchSplit = true;}}}} else {// split只有一位,则已经匹配了isMatchSplit = true;}}if (isMatchSplit) {byte[] part = new byte[i - latestStartIndex];System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);byte[] decryptPart = decryptByPrivateKey(part, privateKey);for (byte b : decryptPart) {allBytes.add(b);}latestStartIndex = i + splitLen;i = latestStartIndex - 1;}}byte[] bytes = new byte[allBytes.size()];{int i = 0;for (Byte b : allBytes) {bytes[i++] = b.byteValue();}}return bytes;}这样总算把遇见的问题解决了,项目中使用的方案是客户端公钥加密,服务器私钥解密,服务器开发人员说是出于效率考虑,所以还是自己写了个程序测试一下真正的效率
List<Person> personList=new ArrayList<>();int testMaxCount=100;//测试的最大数据条数//添加测试数据for(int i=0;i<testMaxCount;i++){Person person =new Person();person.setAge(i);person.setName(String.valueOf(i));personList.add(person);}//FastJson生成json数据String jsonData=JsonUtils.objectToJsonForFastJson(personList);Log.e("MainActivity","加密前json数据 ---->"+jsonData);Log.e("MainActivity","加密前json数据长度 ---->"+jsonData.length());第二步生成秘钥对
KeyPair keyPair=RSAUtils.generateRSAKeyPair(RSAUtils.DEFAULT_KEY_SIZE);// 公钥RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();// 私钥RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();接下来分别使用公钥加密 私钥解密私钥加密 公钥解密//公钥加密long start=System.currentTimeMillis();byte[] encryptBytes=RSAUtils.encryptByPublicKeyForSpilt(jsonData.getBytes(),publicKey.getEncoded());long end=System.currentTimeMillis();Log.e("MainActivity","公钥加密耗时 cost time---->"+(end-start));String encryStr=Base64Encoder.encode(encryptBytes);Log.e("MainActivity","加密后json数据 --1-->"+encryStr);Log.e("MainActivity","加密后json数据长度 --1-->"+encryStr.length());//私钥解密start=System.currentTimeMillis();byte[] decryptBytes= RSAUtils.decryptByPrivateKeyForSpilt(Base64Decoder.decodeToBytes(encryStr),privateKey.getEncoded());String decryStr=new String(decryptBytes);end=System.currentTimeMillis();Log.e("MainActivity","私钥解密耗时 cost time---->"+(end-start));Log.e("MainActivity","解密后json数据 --1-->"+decryStr);//私钥加密start=System.currentTimeMillis();encryptBytes=RSAUtils.encryptByPrivateKeyForSpilt(jsonData.getBytes(),privateKey.getEncoded());end=System.currentTimeMillis();Log.e("MainActivity","私钥加密密耗时 cost time---->"+(end-start));encryStr=Base64Encoder.encode(encryptBytes);Log.e("MainActivity","加密后json数据 --2-->"+encryStr);Log.e("MainActivity","加密后json数据长度 --2-->"+encryStr.length());//公钥解密start=System.currentTimeMillis();decryptBytes= RSAUtils.decryptByPublicKeyForSpilt(Base64Decoder.decodeToBytes(encryStr),publicKey.getEncoded());decryStr=new String(decryptBytes);end=System.currentTimeMillis();Log.e("MainActivity","公钥解密耗时 cost time---->"+(end-start));Log.e("MainActivity","解密后json数据 --2-->"+decryStr);运行结果:
对比发现:私钥的加解密都很耗时,所以可以根据不同的需求采用不能方案来进行加解密。个人觉得服务器要求解密效率高,客户端私钥加密,服务器公钥解密比较好一点
加密后数据大小的变化:数据量差不多是加密前的1.5倍
总结
以上就是关于Android Rsa数据加解密的全部内容,希望这篇文章的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。