RC4에서 key값은 256byte인 S배열을 permutation하는 역할
1. KSA(Key-Scheduling Algorithm)을 통해 256byte의 S배열을 permutation시킨다.
2. PRGA(Pseudo-Random Gerneration Algorithm)을 돌며 평문을 암호화한다.
KSA(Key-Scheduling Algorithm) pseudo codde
for i from 0 to 255
S[i] := i
endfor
j := 0
for i from 0 to 255
j := (j + S[i] + key[i mod keylength]) mod 256
swap values of S[i] and S[j]
endfor
PRGA(Pseudo-Random Gerneration Algorithm) pseudo codde
i := 0
j := 0
while GeneratingOutput:
i := (i + 1) mod 256
j := (j + S[i]) mod 256
swap values of S[i] and S[j]
K := S[(S[i] + S[j]) mod 256]
output K
endwhile
- python code
def KSA(key):
key = map(ord, key)
s = [i for i in range(256)]
j = 0
for i in range(256):
j = (j + s[i] + key[i%len(key)]) % 256
s[i], s[j] = s[j], s[i]
return s
def PRGA(text, s): #s배열로 text에 xor 적용
t_list = map(ord, text)
i, j = (0, 0)
for index in range(len(t_list)) :
i = (i+1) % 256
j = (j + s[i]) % 256
s[i], s[j] = s[j], s[i]
xor_key = s[(s[i] + s[j]) % 256]
t_list[index] = xor_key ^ t_list[index]
result = ''.join(map(chr, t_list))
return result
key = '112233'.decode('hex')
text = '74657374'.decode('hex')
s = KSA(key)
result = PRGA(text, s)
print 'String : ' + result
print 'Tohex : ' + result.encode('hex')
xor로 암호화하기 때문에 따로 복호화 코드는 필요 없다.
위에 key와 text 값을 hex 넣어 주면 된다. ~~
'Programming > Python' 카테고리의 다른 글
| python - dumpcode (0) | 2014.02.26 |
|---|---|
| python - ROL, ROR (2) | 2013.12.14 |
| python HTML, XML 파싱 - BeautifulSoup (0) | 2013.11.21 |
| python SOCKS Proxy 사용 - socksipy (0) | 2013.11.08 |
| python socket관련 - socket, urllib2, httplib (0) | 2013.11.05 |