解析Android資料加密之異或密碼編譯演算法_Android

來源:互聯網
上載者:User

前言:

這幾天被公司臨時拉到去做Android IM即時通訊協定實現,大致看了下他們定的協議,由於之前沒有參與,據說因伺服器效能限制,只達成非明文傳遞,具體原因我不太清楚,不過這裡用的加密方式是採用異或加密。這種加密方式在之前做Android加密記事本的時候採用過這種加密方式。今天已經把用戶端心跳維持、資料包解析對接完了,總結一下這種加密方式。

其他幾種加密方式:

  • Android資料加密之Rsa加密
  • Android資料加密之Aes加密
  • Android資料加密之Des加密
  • Android資料加密之MD5加密
  • Android資料加密之Base64編碼演算法

什麼是異或加密?

異或運算中,如果某個字元(或數值)x 與 一個數值m 進行異或運算得到y,則再用y 與 m 進行異或運算就可以還原為 x ,因此應用這個原理可以實現資料的加密解密功能。

異或運算使用情境?

  • 兩個變數的互換(不藉助第三個變數)
  • 資料的簡單加密解密

異或加密解密實現?

1.固定key的方式

這種方式加密解密 演算法一樣

public byte[] encrypt(byte[] bytes) { if (bytes == null) {  return null; } int len = bytes.length; int key = 0x12; for (int i = 0; i < len; i++) {  bytes[i] ^= key; } return bytes; }

測試加密解密

 byte[] bytes = encrypt("whoislcj".getBytes());//加密 String str1 = new String(encrypt(bytes));//解密

 2.不固定key的方式

加密實現

 public byte[] encrypt(byte[] bytes) { if (bytes == null) {  return null; } int len = bytes.length; int key = 0x12; for (int i = 0; i < len; i++) {  bytes[i] = (byte) (bytes[i] ^ key);  key = bytes[i]; } return bytes; }

 解密實現
 

public byte[] decrypt(byte[] bytes) { if (bytes == null) {  return null; } int len = bytes.length; int key = 0x12; for (int i = len - 1; i > 0; i--) {  bytes[i] = (byte) (bytes[i] ^ bytes[i - 1]); } bytes[0] = (byte) (bytes[0] ^ key); return bytes; }

 測試

 byte[] bytes = encrypt("whoislcj".getBytes());//加密 String str1 = new String(decrypt(bytes));//解密

總結:

位元運算可以實現很多進階,高效的運算。比如說加密,乘法中的n次方就是右移n位,速度還快。IM位元據包採用異或演算法第一能夠實現加密,第二採用異或密碼編譯演算法不會改變位元據的長度這對位元據包封包起到不小的好處。故作此總結。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.