[Crypto, Python] XOR cryption

XOR編碼大概是數一數二簡單卻也很好用的

假如我有一串文字要加密, 還有一個配合加密的key, 可以透過XOR加密來快速做到, 結果還會是binary的格式

而且xor特別的是, 我做兩次一樣的encrypt, 就可以把加密的結果又重新轉出來,缺點則是容易用Frequency analysis就反解出來

網路上有滿多篇都有介紹, 下面這兩篇算是寫比較清楚的一篇

Wiki: http://en.wikipedia.org/wiki/XOR_cipher
Reference1: http://www.evanfosmark.com/2008/06/xor-encryption-with-python/
Reference2: http://stackoverflow.com/questions/2029426/what-is-xor-encryption

以下我也簡單舉個例子使用說明


假如我有一小篇文章要加密 (莎士比亞 - Julius Caesar)
There is a tide in the affairs of men, Which taken at the flood, leads on to fortune. Omitted, all the voyage of their life is bound in shallows and in miseries. On such a full sea are we now afloat. And we must take the current when it serves, or lose our ventures.

我有一把加密的質數用hex表示
D0B55BA51F3BB6071898421570D044A757E8658D55BE753D63BD1179386C3ADB

現在打算用XOR加密這篇文章, key就是那串加密過的質數, 要如何做?

首先XOR加密就是兩個字, 轉成ascii之後, 互相做xor

ex:
a = 'T'
b = 'D'
chr(ord(a)^ord(b)) # xor encrypt

現在會做xor了, 可是又會發現, key遠比文章小, 那怎麼辦呢

很簡單, 我只要一直重複key就好了, 也就是一個一個對應, 等到key被用完第一次, 再從key的頭繼續對應, 一直這樣重複對應到文章結束為止

在上一篇有講過izip跟cycle的使用, 這邊就可以用到了

ex:
from itertools import izip, cycle

def xor_crypt_string(data, key):
    return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))

def main():
    data = "There is a tide in the affairs of men, Which taken at the flood, leads on to fortune. Omitted, all the voyage of their life is bound in shallows and in miseries. On such a full sea are we now afloat. And we must take the current when it serves, or lose our ventures."
    key = "D0B55BA51F3BB6071898421570D044A757E8658D55BE753D63BD1179386C3ADB"
    encrypted = xor_crypt_string(data, key);

    print "== Encrypted =="
    print encrypted

    decrypted = xor_crypt_string(encrypted, key);

    print "== Decrypted =="
    print decrypted

if __name__ == '__main__':
    main()

Output 結果

== Encrypted ==
X'GPb(F'6+RUXVL\WTQV%YFGaXS(]X]\!-AR/S]b%ECQVP/\. nd\'TQ1aZ_fG-bP_EEMW]~X^D0UPaVY[eL^P2ZL#"R\"G*!XCUZ^ScZ2d +E,Q+/B.R..YGDYW\[_ZY7UF]$D
FM']#eQ@_(@'%PE\OSc].3b%V.ZT6op(Wb5SZDKM@SZPD,UW4EGR+LBP![+1FV6@V1h^E_WE&.10dF'[A73PBh
== Decrypted ==
There is a tide in the affairs of men, Which taken at the flood, leads on to fortune. Omitted, all the voyage of their life is bound in shallows and in miseries. On such a full sea are we now afloat. And we must take the current when it serves, or lose our ventures.

留言

這個網誌中的熱門文章

[Linux] Linux下查詢硬體記憶體資訊 Memory Information

[Other] Chrome 重新整理所有開啟頁面

[Python] Simple Socket Server