Last active
May 20, 2024 05:20
-
-
Save taojy123/bc49d69091fa12000019d52e69d35c87 to your computer and use it in GitHub Desktop.
rc4 对称加密,使用 python 和 js 实现
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function rc4(data, key) { | |
var box = Array(256) | |
for (var i = 0; i < 256; i++) { | |
box[i] = i | |
} | |
var x = 0 | |
for (var i = 0; i < 256; i++) { | |
x = (x + box[i] + key.charCodeAt(i % key.length)) % 256 | |
var temp = box[i] | |
box[i] = box[x] | |
box[x] = temp | |
} | |
var x = 0 | |
var y = 0 | |
var out = [] | |
for (var i = 0; i < data.length; i++) | |
{ | |
var code = data.charCodeAt(i) | |
var x = (x + 1) % 256 | |
var y = (y + box[x]) % 256 | |
var temp = box[x] | |
box[x] = box[y] | |
box[y] = temp | |
var k = (box[x] + box[y]) % 256 | |
out.push(String.fromCharCode(code ^ box[k])) | |
} | |
return out.join('') | |
} | |
key = 'mysecret' | |
a = rc4('hello world!', key) | |
console.log(a) | |
b = rc4(a, key) | |
console.log(b) | |
// include >> https://raw.githubusercontent.com/dankogai/js-base64/master/base64.js | |
// Base64.encode(a) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def rc4(data, key): | |
"""RC4 algorithm""" | |
key = [ord(c) for c in key] # or `key = key.encode()` for python3 | |
x = 0 | |
box = list(range(256)) | |
for i in range(256): | |
x = (x + int(box[i]) + int(key[i % len(key)])) % 256 | |
box[i], box[x] = box[x], box[i] | |
x = y = 0 | |
out = [] | |
for char in data: | |
code = ord(char) | |
x = (x + 1) % 256 | |
y = (y + box[x]) % 256 | |
box[x], box[y] = box[y], box[x] | |
k = (box[x] + box[y]) % 256 | |
out.append(chr(code ^ box[k])) | |
return ''.join(out) | |
key = 'mysecret' | |
a = rc4("hello world!", key) | |
print(a) | |
b = rc4(a, key) | |
print(b) | |
import base64 | |
print(base64.b64encode(a.encode())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment