DAY 6
1
Security

RC語音，最小最快最清晰。

## RC4

RC4 由 Ron Rivest 所設計， 他是 RSA的共同設計者（RSA會在日後介紹）。

RC4相較於前面所介紹的加密演算法複雜了很多，所以要花多一點耐心才看得懂。

1.建立一個 S-box（寫作 S）
S-box 包含0-7的數字照順序排列，

2. 決定密鑰

3.建立密鑰列表 K

``````S = [0,1,2,3,4,5,6,7]
K = [1,2,3,1,2,3,1,2]

j = 0
for i in range(8):
j = ( j + S[i] + K[i] ) %8  # "%" 就是取餘數的意思，也就是mod 8 的意思
S[i], S[j] = S[j], S[i]     # 將 S 中的「第i項」跟「第j項」互換
``````

S 會變成 [1,0,2,3,4,5,6,7]

[1, 0, 2, 3, 4, 5, 6, 7]
[1, 3, 2, 0, 4, 5, 6, 7]
[2, 3, 1, 0, 4, 5, 6, 7]
[2, 0, 1, 3, 4, 5, 6, 7]
[2, 0, 1, 3, 7, 5, 6, 4]
[2, 0, 1, 3, 7, 4, 6, 5]
[2, 0, 1, 3, 7, 4, 6, 5]
[2, 0, 1, 3, 7, 5, 6, 4]

``````
i, j = 0, 0
flag = 0
while flag < len(P):

i = (i + 1) % 8
j = (j +S[i]) % 8       # S = [2, 0, 1, 3, 7, 5, 6, 4]
S[i], S[j] = S[j], S[i]
t = (S[i] + S[j] ) % 8
k = S[t]

flag += 1
``````

t = 2+0 = 2
k = S[2] = 1

``````S = [0,1,2,3,4,5,6,7]
K = [1,2,3,1,2,3,1,2]
P = [5,3,6,7]

j = 0
for i in range(8):
j = ( j + S[i] + K[i] ) %8
S[i], S[j] = S[j], S[i]

i, j = 0, 0
flag = 0
c_list = []
while flag < len(P):

i = (i + 1) % 8
j = (j +S[i]) % 8
S[i], S[j] = S[j], S[i]
t = (S[i] + S[j] ) % 8
k = S[t]

k = '{:03b}'.format(k)
p = '{:03b}'.format(P[flag])
c  = ''
for n in range(3):
c += str(int(k[n])^int(p[n]))
c_list.append(int(c, 2))
flag += 1

print(c_list)
``````

RC4在後來被指出他所產生的密鑰並不隨機，存在統計上的偏誤，並且密文有洩漏明文資訊的可能，