简介:

异或加密其实就是利用异或运算的自反性。一个数A 连续异或同样一个数B,最后的结果还是A 自身。即,

A xor B xor B = A

如 Android 数据加密 ---- 总篇 中提到的,对于加密其实就是算法 + **,而对于异或加密算法比较简单。

二战期间,各国为了电报加密,对密码学进行了大量的研究和实践,其中就包括 XOR 加密。

Android 数据加密 ---- 异或加密

战后,美国数学家香农(Claude Shannon)将他的研究成果公开发表,证明了只要满足两个条件,XOR 加密是无法**的。

key的长度大于等于message

key必须是一次性的,且每次都要随机产生

理由很简单,如果每次的 key 都是随机的,那么产生的Cipher Text 具有所有可能的值,而且是均匀分布,无法从Cipher Text看出 Message 的任何特征。也就是说,它具有最大的"信息熵",因此完全不可能**。这被称为 XOR 的"完美保密性"(perfect secrecy)。

满足上面两个条件的 key ,叫做 one-time pad(缩写为OTP),意思是"一次性密码本",因为以前这样的 key 都是印刷成密码本,每次使用的时候,必须从其中挑选key

异或加密是强度极低的一种方式,除非极长的密码,才能确保加密的有效性,但是,使密码达到与数据一致,显然是不可能的,因此,异或加密的数据长度会受到限制。由于异或加密的强度极低,因此,应根据数据库加密的保密性来决定采用什么样的加密技术,如果想获得比较可靠的加密,可以采用分组交换式加密方案。

 

实例:

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 = 呵呵哈哈

 

**保存:

如 Android 数据加密 ---- 总篇 中提到的,数据的加密技术中也包含了**的管理技术,包括**的产生、分配、保存、更换和销毁等各个环节上的保密措施。不论是这里的异或加密,还是其他的加密方式,**的保护十分重要。对于Java 来说,很容易被反编译,这边的**可以通过native 保存(一般so还是很难被破译)或者服务器上。

当然,为了让 XOR 加密更可靠,可以添加一些其他的操作,例如,对数据进行循环的位移。

 

 

参考:

https://blog.csdn.net/chentengkui/article/details/72997534

相关文章: