Android資料加密之Rsa加密_Android

來源:互聯網
上載者:User

前言:

最近無意中和同事交流資料安全傳輸的問題,想起自己曾經使用過的Rsa非對稱式加密演算法,閑下來總結一下。 

其他幾種加密方式:

 •Android資料加密之Rsa加密
 •Android資料加密之Aes加密
 •Android資料加密之Des加密
 •Android資料加密之MD5加密
 •Android資料加密之Base64編碼演算法
 •Android資料加密之SHA安全散列演算法 

什麼是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倍

 以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.