前言:
对于异或加密,在博文 异或加密 已经有了详细说明,这边博文将其用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 = 呵呵哈哈