贝贝:啊!我看见了一只蜘蛛!
贝贝的梦:
Enter your plaintext
贝贝输入:Hi,how are you?
Enter your key
贝贝输入:include
有个按钮"Encrypt”
贝贝点击了一下:
Jl%f{lMD$m#¸
哇,对了!
第二天:
贝贝:我昨晚上做了个奇怪的梦,是RC4加密解密,小米帮写一下代码吧!
小米:好吧。
c++:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> initializeSBox(string key) {
vector<int> sBox(256);
int keyLength = key.length();
int j = 0;
for (int i = 0; i < 256; i++) {
sBox[i] = i;
}
for (int i = 0; i < 256; i++) {
j = (j + sBox[i] + key[i % keyLength]) % 256;
swap(sBox[i], sBox[j]);
}
return sBox;
}
string rc4Encrypt(string plaintext, string key) {
vector<int> sBox = initializeSBox(key);
int i = 0;
int j = 0;
string ciphertext = "";
for (int k = 0; k < plaintext.length(); k++) {
i = (i + 1) % 256;
j = (j + sBox[i]) % 256;
swap(sBox[i], sBox[j]);
int t = (sBox[i] + sBox[j]) % 256;
int cipherChar = plaintext[k] ^ sBox[t];
ciphertext += cipherChar;
}
return ciphertext;
}
string rc4Decrypt(string ciphertext, string key) {
return rc4Encrypt(ciphertext, key);
}
int main() {
string plaintext = "Hello, World!";
string key = "SecretKey";
string ciphertext = rc4Encrypt(plaintext, key);
cout << "Encrypted Text: " << ciphertext << endl;
string decryptedText = rc4Decrypt(ciphertext, key);
cout << "Decrypted Text: " << decryptedText << endl;
return 0;
}
贝贝:看起来很棒!可我要HTML的。
小米:
<!DOCTYPE html>
<html>
<head>
<title>RC4 Encryption</title>
<script type="text/javascript">
function rc4Encrypt() {
var plaintext = document.getElementById("plaintext").value;
var key = document.getElementById("key").value;
var sBox = initializeSBox(key);
var i = 0;
var j = 0;
var ciphertext = "";
for(var k = 0; k < plaintext.length; k++) {
i = (i + 1) % 256;
j = (j + sBox[i]) % 256;
swap(sBox[i], sBox[j]);
var t = (sBox[i] + sBox[j]) % 256;
var cipherChar = plaintext.charCodeAt(k) ^ sBox[t];
ciphertext += String.fromCharCode(cipherChar);
}
document.getElementById("ciphertext").innerHTML = ciphertext;
}
function swap(a, b) {
var temp = a;
a = b;
b = temp;
}
function initializeSBox(key) {
var sBox = [];
var keyLength = key.length;
var j = 0;
for(var i = 0; i < 256; i++) {
sBox[i] = i;
}
for(var i = 0; i < 256; i++) {
j = (j + sBox[i] + key.charCodeAt(i % keyLength)) % 256;
swap(sBox[i], sBox[j]);
}
return sBox;
}
</script>
</head>
<body>
<h1>RC4 Encryption</h1>
<label for="plaintext">Plaintext:</label>
<input type="text" id="plaintext" placeholder="Enter your plaintext" required><br><br>
<label for="key">Key:</label>
<input type="password" id="key" placeholder="Enter your key" required><br><br>
<button onclick="rc4Encrypt()">Encrypt</button><br><br>
<label for="ciphertext">Ciphertext:</label>
<textarea id="ciphertext"></textarea>
</body>
</html>
完美!(加nice)