溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Android中利用RSA算法進行加密和解密

發(fā)布時間:2021-04-08 16:44:35 來源:億速云 閱讀:374 作者:Leah 欄目:移動開發(fā)

這期內(nèi)容當中小編將會給大家?guī)碛嘘P怎么在Android中利用RSA算法進行加密和解密,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

一、公鑰加密和私鑰解密

  /**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);
    // 加密數(shù)據(jù)
    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);
    // 解密數(shù)據(jù)
    Cipher cp = Cipher.getInstance(TRANSFORMATION);
    cp.init(Cipher.DECRYPT_MODE, keyPrivate);
    byte[] arr = cp.doFinal(encrypted);
    return arr;
  }

1.data是要加密的數(shù)據(jù),如果是字符串則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", "加密后的數(shù)據(jù):" + StringUtils.byteArrayToString(encrypt));
    
    //用私鑰解密
    byte[] decrypt = RSAUtils.decryptByPrivateKey(encrypt, privateKey);
    Log.d("TAG", "解密后的數(shù)據(jù):" + new String(decrypt, "utf-8"));
  } catch (Exception e) {
    e.printStackTrace();
  }

怎么在Android中利用RSA算法進行加密和解密

2.從文件中讀取公鑰

怎么在Android中利用RSA算法進行加密和解密

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", "加密后的數(shù)據(jù):" + 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", "解密后的數(shù)據(jù):" + new String(decrypt, "utf-8"));
    } catch (Exception e) {
      e.printStackTrace();
    }

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

當加密的數(shù)據(jù)過長時,會出現(xiàn)javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes的異常。rsa算法規(guī)定一次加密的數(shù)據(jù)不能超過生成密鑰對時的keyLength/8-11,keyLength一般是1024個字節(jié),則加密的數(shù)據(jù)不能超過117個字節(jié)

  /**秘鑰默認長度*/
  public static final int DEFAULT_KEY_SIZE = 1024;
  /**加密的數(shù)據(jù)最大的字節(jié)數(shù),即117個字節(jié)*/
  public static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11;
  /**當加密的數(shù)據(jù)超過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,則表明已經(jīng)確認是split段
                isMatchSplit = true;
              }
            }
          }
        } else {
          // split只有一位,則已經(jīng)匹配了
          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", "要加密的數(shù)據(jù):" + data + ", 要加密的數(shù)據(jù)長度:" + data.length());
    try {
      //分段加密
      byte[] encrypt = RSAUtils.encryptByPublicKeyForSpilt(data.getBytes(), publicKey);
      Log.d("TAG", "加密后的數(shù)據(jù):" + StringUtils.byteArrayToString(encrypt));
      
      //分段解密
      byte[] decrypt = RSAUtils.decryptByPrivateKeyForSpilt(encrypt, privateKey);
      Log.d("TAG", "解密后的數(shù)據(jù):" + new String(decrypt, "utf-8"));
    } catch (Exception e) {
      e.printStackTrace();
    }

三、生成密鑰對

怎么在Android中利用RSA算法進行加密和解密

  /** 生成密鑰對,即公鑰和私鑰。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...等等一長串用-拼接的數(shù)字 */
  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中利用RSA算法進行加密和解密

上述就是小編為大家分享的怎么在Android中利用RSA算法進行加密和解密了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI