Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android RSA加密和解密

Android使用RSA加密和解密的示例代码

作者:wmjwmj

本篇文章主要介绍了Android使用RSA加密和解密的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

一、公钥加密和私钥解密

  /**RSA算法*/
  public static final String RSA = "RSA";
  /**加密方式,android的*/
// public static final String TRANSFORMATION = "RSA/None/NoPadding";
  /**加密方式,标准jdk的*/
  public static final String TRANSFORMATION = "RSA/None/PKCS1Padding";

  /** 使用公钥加密 */
  public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
    // 得到公钥对象
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey pubKey = keyFactory.generatePublic(keySpec);
    // 加密数据
    Cipher cp = Cipher.getInstance(TRANSFORMATION);
    cp.init(Cipher.ENCRYPT_MODE, pubKey);
    return cp.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(TRANSFORMATION);
    cp.init(Cipher.DECRYPT_MODE, keyPrivate);
    byte[] arr = cp.doFinal(encrypted);
    return arr;
  }

1.data是要加密的数据,如果是字符串则getBytes。publicKey是公钥,privateKey是私钥。自定义密钥对测试

  String data = "hello world";
  try {
    int keyLength = 1024;
    //生成密钥对
    KeyPair keyPair = RSAUtils.generateRSAKeyPair(keyLength);
    //获取公钥
    byte[] publicKey = RSAUtils.getPublicKey(keyPair);
    //获取私钥
    byte[] privateKey = RSAUtils.getPrivateKey(keyPair);
    
    //用公钥加密
    byte[] encrypt = RSAUtils.encryptByPublicKey(data.getBytes(), publicKey);
    Log.d("TAG", "加密后的数据:" + StringUtils.byteArrayToString(encrypt));
    
    //用私钥解密
    byte[] decrypt = RSAUtils.decryptByPrivateKey(encrypt, privateKey);
    Log.d("TAG", "解密后的数据:" + new String(decrypt, "utf-8"));
  } catch (Exception e) {
    e.printStackTrace();
  }

2.从文件中读取公钥

    String data = "hello world";
    //读取公钥文件
    String publicKeyString = IOUtils.readAssetsFile(this, "rsa_public_key.pem");
    //base64解码
    byte[] publicKey = Base64Utils.decodeToBytes(publicKeyString);
    
    try {
      //加密
      byte[] encrypt = RSAUtils.encryptByPublicKey(data.getBytes(), publicKey);
      Log.d("TAG", "加密后的数据:" + StringUtils.byteArrayToString(encrypt));
      
//     //读取私钥文件
//     String privateKeyString = IOUtils.readAssetsFile(this, "rsa_private_key.pem");
//     //base64解码
//     byte[] privateKey = Base64Utils.decodeToBytes(privateKeyString);
//     //解密
//     byte[] decrypt = RSAUtils.decryptByPrivateKey(encrypt, privateKey);
//     Log.d("TAG", "解密后的数据:" + new String(decrypt, "utf-8"));
    } catch (Exception e) {
      e.printStackTrace();
    }

二、公钥分段加密和私钥分段解密

当加密的数据过长时,会出现javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes的异常。rsa算法规定一次加密的数据不能超过生成密钥对时的keyLength/8-11,keyLength一般是1024个字节,则加密的数据不能超过117个字节

  /**秘钥默认长度*/
  public static final int DEFAULT_KEY_SIZE = 1024;
  /**加密的数据最大的字节数,即117个字节*/
  public static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11;
  /**当加密的数据超过DEFAULT_BUFFERSIZE,则使用分段加密*/
  public static final byte[] DEFAULT_SPLIT = "#PART#".getBytes();

  /** 使用公钥分段加密 */
  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;
  }

  /** 使用私钥分段解密 */
  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;
  }

测试分段加密和解密

    String data = "hello world hello world hello world hello world hello world hello world hello world hello world " +
        "hello world hello world hello world hello world hello world hello world hello world hello world hello world " +
        "hello world hello world hello world hello world hello world hello world hello world hello world hello world ";
    Log.d("TAG", "要加密的数据:" + data + ", 要加密的数据长度:" + data.length());
    try {
      //分段加密
      byte[] encrypt = RSAUtils.encryptByPublicKeyForSpilt(data.getBytes(), publicKey);
      Log.d("TAG", "加密后的数据:" + StringUtils.byteArrayToString(encrypt));
      
      //分段解密
      byte[] decrypt = RSAUtils.decryptByPrivateKeyForSpilt(encrypt, privateKey);
      Log.d("TAG", "解密后的数据:" + new String(decrypt, "utf-8"));
    } catch (Exception e) {
      e.printStackTrace();
    }

三、生成密钥对

  /** 生成密钥对,即公钥和私钥。key长度是512-2048,一般为1024 */
  public static KeyPair generateRSAKeyPair(int keyLength) throws NoSuchAlgorithmException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
    kpg.initialize(keyLength);
    return kpg.genKeyPair();
  }

  /** 获取公钥,打印为48-12613448136942-12272-122-913111503-126115048-12...等等一长串用-拼接的数字 */
  public static byte[] getPublicKey(KeyPair keyPair) {
    RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
    return rsaPublicKey.getEncoded();
  }

  /** 获取私钥,同上 */
  public static byte[] getPrivateKey(KeyPair keyPair) {
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    return rsaPrivateKey.getEncoded();
  }

生成公钥和私钥后,用base64编码

    int keyLength = 1024;
    try {
      //生成密钥对
      KeyPair keyPair = RSAUtils.generateRSAKeyPair(keyLength);

      //获取公钥
      byte[] publicKey = RSAUtils.getPublicKey(keyPair);
      Log.d("TAG", "公钥:" + StringUtils.byteArrayToString(publicKey));
      //公钥用base64编码
      String encodePublic = Base64Utils.encodeToString(publicKey);
      Log.d("TAG", "base64编码的公钥:" + encodePublic);

      //获取私钥
      byte[] privateKey = RSAUtils.getPrivateKey(keyPair);
      Log.d("TAG", "私钥:" + StringUtils.byteArrayToString(privateKey));
      //私钥用base64编码
      String encodePrivate = Base64Utils.encodeToString(privateKey);
      Log.d("TAG", "base64编码的私钥:" + encodePrivate);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }    

其它

一、android加密的数据服务器上无法解密?

android的rsa加密方式是RSA/ECB/NoPadding,而标准jdk是RSA/ECB/PKCS1Padding,所以加密时要设置标准jdk的加密方式

二、base64编码。因为不同的设备对字符的处理方式不同,字符有可能处理出错,不利于传输。所以先把数据做base64编码,变成可见字符,减少出错
官方提供的base64类,Base64.encode编码,Base64.decode解码。用这个会有换行符,需要自定义

三、rsa是非对称加密算法。依赖于大数计算,加密速度比des慢,通常只用于加密少量数据或密钥

四、公钥加密比私钥加密块,公钥解密比私钥解密慢。加密后的数据大概是加密前的1.5倍

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文