当前位置: 移动技术网 > IT编程>移动开发>Android > Android数据加密之Rsa加密的简单实现

Android数据加密之Rsa加密的简单实现

2019年07月24日  | 移动技术网IT编程  | 我要评论

侯耀华小品,肖素丽,crescendo中文音译

最近无意中和同事交流数据安全传输的问题,想起自己曾经使用过的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。

最终得到的n和e就是“公钥”,d就是“私钥”,发送方使用n去加密数据,接收方只有使用d才能解开数据内容。

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

该如何使用呢?

第一步:首先生成秘钥对

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

关于加密填充方式:之前以为上面这些操作就能实现rsa加解密,以为万事大吉了,呵呵,这事还没完,悲剧还是发生了,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;
  }

这样总算把遇见的问题解决了,项目中使用的方案是客户端公钥加密,服务器私钥解密,服务器开发人员说是出于效率考虑,所以还是自己写了个程序测试一下真正的效率

第一步:准备100条对象数据

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加密的简单实现全部内容了,希望大家多多支持移动技术网~

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网