Android 数据加密之Rsa加密

什么是Rsa加密

RSA算法是最流行的公钥密码算法,使用长度可以变化的密钥。RSA是第一个既能用于数据加密也能用于数字签名的算法。

RSA算法原理如下:

1.随机选择两个大质数p和q,p不等于q,计算N=pq;
2.选择一个大于1小于N的自然数e,e必须与(p-1)(q-1)互素。
3.用公式计算出d:d×e = 1 (mod (p-1)(q-1)) 。
4.销毁p和q。

RSA的安全性依赖于大数分解,小于1024位的N已经被证明是不安全的,而且由于RSA算法进行的都是大数计算,使得RSA最快的情况也比DES慢上倍,这是RSA最大的缺陷,因此通常只能用于加密少量数据或者加密密钥,但RSA仍然不失为一种高强度的算法。

具体实现

全局变量解说

 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;// 当前秘钥支持加密的最大字节数
  • 首先生成秘钥对
 /**
     * 随机生成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;
}

遇到的问题

关于加密填充方式:Android这边加密过的数据,服务器端死活解密不了,原来android系统的RSA实现是"RSA/None/NoPadding",而标准JDK实现是"RSA/None/PKCS1Padding",这造成了在android机上加密后无法在服务器上解密的原因,所以在实现的时候这个一定要注意。

实现分段加密:搞定了填充方式之后又自信的认为万事大吉了,可是意外还是发生了,RSA非对称加密对内容长度有限制,1024位key的最多只能加密127位数据,否则就会报错(javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes) , RSA 是常用的非对称加密算法。最近使用时却出现了“不正确的长度”的异常,研究发现是由于待加密的数据超长所致。RSA 算法规定:待加密的字节数不能超过密钥的长度值除以 8 再减去 11(即:KeySize / 8 - 11),而加密后得到密文的字节数,正好是密钥的长度值除以 8(即:KeySize / 8)。

为解决上述问题实现分段加密

公钥分段加密

/**
  * 用公钥对字符串进行分段加密
  *
  */
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;
    }

测试

第一步:准备数据

public String jsonData() {
        List<Person> personList = new ArrayList<>();
        int testMaxCount = 1000;//测试的最大数据条数
        //添加测试数据
        for (int i = 0; i < testMaxCount; i++) {
            Person person = new Person();
            person.setName(String.valueOf(i));
            personList.add(person);
        }

        Gson gson = new Gson();
        return gson.toJson(personList).toString();
    }

第二步生成秘钥对

  //生成秘钥对
        KeyPair keyPair = RsaUtil.generateRSAKeyPair(RsaUtil.DEFAULT_KEY_SIZE);
        //公钥
        PublicKey publicKey = keyPair.getPublic();
        //私钥
        PrivateKey privateKey = keyPair.getPrivate();

第三步:进行加密解密

 long start;
        long end;
        byte[] encryptBytes = new byte[0];
        byte[] decryptBytes = new byte[0];
        String encryStr, decryStr;

        try {
            //公钥加密
            start = System.currentTimeMillis();

            encryptBytes = RsaUtil.encryptByPublicKeyForSpilt(jsonData().getBytes(), publicKey.getEncoded());
            end = System.currentTimeMillis();
            Log.e("MainActivity", "公钥加密耗时 cost time---->" + (end - start));
            encryStr = Base64Encoder.encode(encryptBytes);
//            Log.e("MainActivity", "加密后json数据 --1-->" + encryStr);
            Log.e("MainActivity", "加密后json数据长度 --1-->" + encryStr.length());

            //私钥解密
            start = System.currentTimeMillis();
            decryptBytes = RsaUtil.decryptByPrivateKeyForSpilt(Base64Decoder.decodeToBytes(encryStr), privateKey.getEncoded());
            decryStr = new String(decryptBytes);
            end = System.currentTimeMillis();
            Log.e("MainActivity", "私钥解密耗时 cost time---->" + (end - start));
            Log.e("MainActivity", "解密后json数据 --1-->" + decryStr);
        } catch (Exception e) {
            e.printStackTrace();
        }



        try {

            //私钥加密
            start = System.currentTimeMillis();
            encryptBytes = RsaUtil.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 = RsaUtil.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);

        } catch (Exception e) {
            e.printStackTrace();
        }

这里写图片描述

对比发现

  • 私钥的加解密都很耗时,所以可以根据不同的需求采用不能方案来进行加解密。个人觉得服务器要求解密效率高,客户端私钥加密,服务器公钥解密比较好一点
  • 加密后数据大小的变化:数据量差不多是加密前的1.5倍
RSA封装类 ,完整的RSA加密和解密 public class RSAUtilEncrypt { public static final String KEY_ALGORTHM = "RSA";// public static final String KEY_ALGORTHM_RSA_ECB_PKCS1PADDING = "RSA/ECB/PKCS1Padding"; public static String RSA_PUBLIC_KEY = "rsa_public_key"; public static String RSA_PRIVATE_KEY = "rsa_private_key"; private int KeySize = 1024; private Map keyMap; private static String RSA = "RSA"; private static PublicKey publickey; public RSAUtilEncrypt(int KeySize,String publickey) { this.KeySize = KeySize; try { this.publickey=generatePublicKeyByString(publickey); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private RSAPublicKey generatePublicKeyByString(String publicKeyStr) throws Exception { try { BASE64Decoder base64Decoder = new BASE64Decoder(); byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("No Algorthm,Checked by cemung!"); } catch (InvalidKeySpecException e) { throw new Exception("InvalidKeySpec!"); } catch (IOException e) { throw new Exception("Io exception!"); } catch (NullPointerException e) { throw new Exception("Illegle pointer reference!"); } } // Encypt public byte[] RSAEncrypt(byte[] data, RSAPublicKey publickey) throws Exception { Cipher cipher = Cipher.getInstance(KEY_ALGORTHM_RSA_ECB_PKCS1PADDING); cipher.init(Cipher.ENCRYPT_MODE, this.publickey); byte[] cipherbytes = cipher.doFinal(data); return cipherbytes; } // Encypt public byte[] RSAEncrypt(byte[] data) throws Exception { Cipher cipher = Cipher.getInstance(KEY_ALGORTHM_RSA_ECB_PKCS1PADDING); cipher.init(Cipher.ENCRYPT_MODE, this.publickey); byte[] cipherbytes = cipher.doFinal(data); return cipherbytes; } // Get Public key with format byte[] public byte[] getPublicKeyByte() { RSAPublicKey pubkey = (RSAPublicKey) keyMap.get(RSA_PUBLIC_KEY); return pubkey.getEncoded(); } public static byte[] decryptBASE64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key); } public static String encryptBASE64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key); } public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); } public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); } public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicKey); return cipher.doFinal(data); } 使用方法 private RSAUtilEncrypt rsa = new RSAUtilEncrypt(1024, publikey); /* * 给信息加密,获取密文 */ public String getCiphertext(String str_encrode) { try { byte[] estr = rsa.RSAEncrypt(str_encrode.getBytes()); // 密文 String ciphertext = Base64.encodeToString(estr, Base64.DEFAULT); return ciphertext; } catch (Exception e) { e.printStackTrace(); } return null; } 有疑问的留言
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值