Android 中資料加密 ---- 異或加密
阿新 • • 發佈:2018-12-21
前言:
對於異或加密,在博文 異或加密 已經有了詳細說明,這邊博文將其用Android 實現。
例項:
Activity 中新增兩個呼叫的程式碼:
private void testEncryptionXOR() { Button exor = (Button) findViewById(R.id.encrypt_xor); exor.setOnClickListener(this); Button dxor = (Button) findViewById(R.id.decrypt_xor); dxor.setOnClickListener(this); mXOREncryption = new XOREncryption(KEY_XOR); } private void xorEncryption() { // String strSource = "hliuhiufhliuhsd;jfijso;goshgosjogijsgo;j"; String strSource = "呵呵哈哈"; if (mXOREncryption != null) { Log.d(TAG, "==== strSource = " + strSource); mStrEncrypted = mXOREncryption.strEncrypt(strSource); Log.d(TAG, "==== strEncrypted = " + mStrEncrypted); } } private void xorDecrypted() { if (mXOREncryption != null) { String ret = mXOREncryption.strDecrypt(mStrEncrypted); Log.d(TAG, "==== strDecrypted = " + ret); } }
XOREncryption 程式碼(後期會進一步補充對於檔案的XOR 加密):
public class XOREncryption { private final String mKey; public XOREncryption(String key) { mKey = key; if (TextUtils.isEmpty(mKey)) { throw new IllegalArgumentException("key is empty..."); } } public String strEncrypt(final String strSource) { int i, j; StringBuilder sb = new StringBuilder(); for (i = 0, j = 0; i < strSource.length(); i++) { j = i % mKey.length(); sb.append((char) (strSource.charAt(i) ^ mKey.charAt(j))); } return sb.toString(); } // 再次進行異或運算就可以解密 public String strDecrypt(final String strSource) { return strEncrypt(strSource); } }
執行的結果:
--------- beginning of main --------- beginning of system 11-29 06:28:53.221 3633 3633 D TestEncryptionActivity: ==== strSource = 呵呵哈哈 11-29 06:28:53.221 3633 3633 D TestEncryptionActivity: ==== strEncrypted = 吔向咭咢 11-29 06:28:55.027 3633 3633 D TestEncryptionActivity: ==== strDecrypted = 呵呵哈哈