[421] | 1 | # $Id: p3.py,v 1.2 2003/11/18 19:04:03 phr Exp phr $ |
---|
| 2 | |
---|
| 3 | # Simple p3 encryption "algorithm": it's just SHA used as a stream |
---|
| 4 | # cipher in output feedback mode. |
---|
| 5 | |
---|
| 6 | # Author: Paul Rubin, Fort GNOX Cryptography, <phr-crypto at nightsong.com>. |
---|
| 7 | # Algorithmic advice from David Wagner, Richard Parker, Bryan |
---|
| 8 | # Olson, and Paul Crowley on sci.crypt is gratefully acknowledged. |
---|
| 9 | |
---|
| 10 | # Copyright 2002,2003 by Paul Rubin |
---|
| 11 | # Copying license: same as Python 2.3 license |
---|
| 12 | |
---|
| 13 | # Please include this revision number in any bug reports: $Revision: 1.2 $. |
---|
| 14 | |
---|
| 15 | from string import join |
---|
| 16 | from array import array |
---|
| 17 | import sha |
---|
| 18 | import getpass |
---|
| 19 | from time import time |
---|
| 20 | |
---|
| 21 | |
---|
| 22 | class CryptError(Exception): pass |
---|
| 23 | def _hash(str): return sha.new(str).digest() |
---|
| 24 | |
---|
| 25 | _ivlen = 16 |
---|
| 26 | _maclen = 8 |
---|
| 27 | _state = _hash(`time()`) |
---|
| 28 | |
---|
| 29 | try: |
---|
| 30 | import os |
---|
| 31 | _pid = `os.getpid()` |
---|
| 32 | except ImportError, AttributeError: |
---|
| 33 | _pid = '' |
---|
| 34 | |
---|
| 35 | def _expand_key(key, clen): |
---|
| 36 | blocks = (clen+19)/20 |
---|
| 37 | xkey=[] |
---|
| 38 | seed=key |
---|
| 39 | for i in xrange(blocks): |
---|
| 40 | seed=sha.new(key+seed).digest() |
---|
| 41 | xkey.append(seed) |
---|
| 42 | j = join(xkey,'') |
---|
| 43 | return array ('L', j) |
---|
| 44 | |
---|
| 45 | def p3_encrypt(plain,key): |
---|
| 46 | global _state |
---|
| 47 | H = _hash |
---|
| 48 | |
---|
| 49 | # change _state BEFORE using it to compute nonce, in case there's |
---|
| 50 | # a thread switch between computing the nonce and folding it into |
---|
| 51 | # the state. This way if two threads compute a nonce from the |
---|
| 52 | # same data, they won't both get the same nonce. (There's still |
---|
| 53 | # a small danger of a duplicate nonce--see below). |
---|
| 54 | _state = 'X'+_state |
---|
| 55 | |
---|
| 56 | # Attempt to make nlist unique for each call, so we can get a |
---|
| 57 | # unique nonce. It might be good to include a process ID or |
---|
| 58 | # something, but I don't know if that's portable between OS's. |
---|
| 59 | # Since is based partly on both the key and plaintext, in the |
---|
| 60 | # worst case (encrypting the same plaintext with the same key in |
---|
| 61 | # two separate Python instances at the same time), you might get |
---|
| 62 | # identical ciphertexts for the identical plaintexts, which would |
---|
| 63 | # be a security failure in some applications. Be careful. |
---|
| 64 | nlist = [`time()`, _pid, _state, `len(plain)`,plain, key] |
---|
| 65 | nonce = H(join(nlist,','))[:_ivlen] |
---|
| 66 | _state = H('update2'+_state+nonce) |
---|
| 67 | k_enc, k_auth = H('enc'+key+nonce), H('auth'+key+nonce) |
---|
| 68 | n=len(plain) # cipher size not counting IV |
---|
| 69 | |
---|
| 70 | stream = array('L', plain+'0000'[n&3:]) # pad to fill 32-bit words |
---|
| 71 | xkey = _expand_key(k_enc, n+4) |
---|
| 72 | for i in xrange(len(stream)): |
---|
| 73 | stream[i] = stream[i] ^ xkey[i] |
---|
| 74 | ct = nonce + stream.tostring()[:n] |
---|
| 75 | auth = _hmac(ct, k_auth) |
---|
| 76 | return ct + auth[:_maclen] |
---|
| 77 | |
---|
| 78 | def p3_decrypt(cipher,key): |
---|
| 79 | H = _hash |
---|
| 80 | n=len(cipher)-_ivlen-_maclen # length of ciphertext |
---|
| 81 | if n < 0: |
---|
| 82 | raise CryptError, "invalid ciphertext" |
---|
| 83 | nonce,stream,auth = \ |
---|
| 84 | cipher[:_ivlen], cipher[_ivlen:-_maclen]+'0000'[n&3:],cipher[-_maclen:] |
---|
| 85 | k_enc, k_auth = H('enc'+key+nonce), H('auth'+key+nonce) |
---|
| 86 | vauth = _hmac (cipher[:-_maclen], k_auth)[:_maclen] |
---|
| 87 | if auth != vauth: |
---|
| 88 | raise CryptError, "invalid key or ciphertext" |
---|
| 89 | |
---|
| 90 | stream = array('L', stream) |
---|
| 91 | xkey = _expand_key (k_enc, n+4) |
---|
| 92 | for i in xrange (len(stream)): |
---|
| 93 | stream[i] = stream[i] ^ xkey[i] |
---|
| 94 | plain = stream.tostring()[:n] |
---|
| 95 | return plain |
---|
| 96 | |
---|
| 97 | # RFC 2104 HMAC message authentication code |
---|
| 98 | # This implementation is faster than Python 2.2's hmac.py, and also works in |
---|
| 99 | # old Python versions (at least as old as 1.5.2). |
---|
| 100 | from string import translate |
---|
| 101 | def _hmac_setup(): |
---|
| 102 | global _ipad, _opad, _itrans, _otrans |
---|
| 103 | _itrans = array('B',[0]*256) |
---|
| 104 | _otrans = array('B',[0]*256) |
---|
| 105 | for i in xrange(256): |
---|
| 106 | _itrans[i] = i ^ 0x36 |
---|
| 107 | _otrans[i] = i ^ 0x5c |
---|
| 108 | _itrans = _itrans.tostring() |
---|
| 109 | _otrans = _otrans.tostring() |
---|
| 110 | |
---|
| 111 | _ipad = '\x36'*64 |
---|
| 112 | _opad = '\x5c'*64 |
---|
| 113 | |
---|
| 114 | def _hmac(msg, key): |
---|
| 115 | if len(key)>64: |
---|
| 116 | key=sha.new(key).digest() |
---|
| 117 | ki = (translate(key,_itrans)+_ipad)[:64] # inner |
---|
| 118 | ko = (translate(key,_otrans)+_opad)[:64] # outer |
---|
| 119 | return sha.new(ko+sha.new(ki+msg).digest()).digest() |
---|
| 120 | |
---|
| 121 | # |
---|
| 122 | # benchmark and unit test |
---|
| 123 | # |
---|
| 124 | |
---|
| 125 | def _time_p3(n=1000,len=20): |
---|
| 126 | plain="a"*len |
---|
| 127 | t=time() |
---|
| 128 | for i in xrange(n): |
---|
| 129 | p3_encrypt(plain,"abcdefgh") |
---|
| 130 | dt=time()-t |
---|
| 131 | print "plain p3:", n,len,dt,"sec =",n*len/dt,"bytes/sec" |
---|
| 132 | |
---|
| 133 | def _speed(): |
---|
| 134 | _time_p3(len=5) |
---|
| 135 | _time_p3() |
---|
| 136 | _time_p3(len=200) |
---|
| 137 | _time_p3(len=2000,n=100) |
---|
| 138 | |
---|
| 139 | def _test(): |
---|
| 140 | e=p3_encrypt |
---|
| 141 | d=p3_decrypt |
---|
| 142 | |
---|
| 143 | plain="test plaintext" |
---|
| 144 | key = "test key" |
---|
| 145 | c1 = e(plain,key) |
---|
| 146 | c2 = e(plain,key) |
---|
| 147 | assert c1!=c2 |
---|
| 148 | assert d(c2,key)==plain |
---|
| 149 | assert d(c1,key)==plain |
---|
| 150 | c3 = c2[:20]+chr(1+ord(c2[20]))+c2[21:] # change one ciphertext character |
---|
| 151 | |
---|
| 152 | try: |
---|
| 153 | print d(c3,key) # should throw exception |
---|
| 154 | print "auth verification failure" |
---|
| 155 | except CryptError: |
---|
| 156 | pass |
---|
| 157 | |
---|
| 158 | try: |
---|
| 159 | print d(c2,'wrong key') # should throw exception |
---|
| 160 | print "test failure" |
---|
| 161 | except CryptError: |
---|
| 162 | pass |
---|
| 163 | |
---|
| 164 | |
---|
| 165 | def encrypt(instring,key=None): |
---|
| 166 | """Encrypt the input string |
---|
| 167 | |
---|
| 168 | Encrypts the input string or the string contained in the file |
---|
| 169 | with name <instring>. Uses encryption key <key> |
---|
| 170 | """ |
---|
| 171 | |
---|
| 172 | try: |
---|
| 173 | if os.path.exists(instring): |
---|
| 174 | instring = open(instring,'r').read().strip() |
---|
| 175 | except: |
---|
| 176 | pass |
---|
| 177 | |
---|
| 178 | if key is None: |
---|
| 179 | key = getpass.getuser() |
---|
| 180 | return 'cry'+p3_encrypt(instring,key)+'pto' |
---|
| 181 | |
---|
| 182 | def decrypt(instring,key=None): |
---|
| 183 | """Decrypt the input string |
---|
| 184 | |
---|
| 185 | Decrypts the input string or the string contained in the file |
---|
| 186 | with name <instring>. Uses encryption key <key>. If the input |
---|
| 187 | string is not encrypted, just returns it. |
---|
| 188 | """ |
---|
| 189 | |
---|
| 190 | try: |
---|
| 191 | if os.path.exists(instring): |
---|
| 192 | instring = open(instring,'r').read().strip() |
---|
| 193 | except: |
---|
| 194 | pass |
---|
| 195 | |
---|
| 196 | ins = instring.strip() |
---|
| 197 | #if re.search('^cry.*pto$',ins): |
---|
| 198 | if ins[:3]+ins[-3:] == 'crypto': |
---|
| 199 | if key is None: |
---|
| 200 | key = getpass.getuser() |
---|
| 201 | ins = ins[3:-3] |
---|
| 202 | return p3_decrypt(ins,key) |
---|
| 203 | else: |
---|
| 204 | return instring |
---|
| 205 | |
---|
| 206 | |
---|
| 207 | _hmac_setup() |
---|
| 208 | _test() |
---|
| 209 | # _speed() # uncomment to run speed test |
---|