嗨,我正试图在Java中实现RC4算法。我发现这个code为帮助我理解这个想法的例子:RC4加密java
public class RC4 {
private int[] S = new int[256];
private int[] T = new int[256];
private int keylen;
public RC4(byte[] key) throws Exception {
if (key.length < 1 || key.length > 256) {
throw new Exception("key must be between 1 and 256 bytes");
} else {
keylen = key.length;
for (int i = 0; i < 256; i++) {
S[i] = i;
T[i] = key[i % keylen];
}
int j = 0;
for (int i = 0; i < 256; i++) {
j = (j + S[i] + T[i]) % 256;
S[i] ^= S[j];
S[j] ^= S[i];
S[i] ^= S[j];
}
}
}
public int[] encrypt(int[] plaintext) {
int[] ciphertext = new int[plaintext.length];
int i = 0, j = 0, k, t;
for (int counter = 0; counter < plaintext.length; counter++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
S[i] ^= S[j];
S[j] ^= S[i];
S[i] ^= S[j];
t = (S[i] + S[j]) % 256;
k = S[t];
ciphertext[counter] = plaintext[counter]^k;
}
return ciphertext;
}
public int[] decrypt(int[] ciphertext) {
return encrypt(ciphertext);
}
}
我有几个问题:
为什么是纯文本的
int
阵列在上面的代码?当我测试这个代码时,我得到了奇怪的结果,有人可以向我解释一下吗?在这里我的代码进行测试:
public class RC4_Main { public static void main(String args[]) throws Exception { String keyword = "hello"; byte[] keytest = keyword.getBytes(); //convert keyword to byte int[] text = {1, 2, 3, 4, 5}; // text as 12345 RC4 rc4 = new RC4(keytest); System.out.print("\noriginal text: "); for (int i = 0; i < text.length; i++) { System.out.print(text[i]); } int[] cipher = rc4.encrypt(text); //encryption System.out.print("\ncipher: "); for (int i = 0; i < cipher.length; i++) { System.out.print(cipher[i]); } int[] backtext = rc4.decrypt(cipher); //decryption System.out.print("\nback to text: "); for (int i = 0; i < backtext.length; i++) { System.out.print(backtext[i]); } System.out.println(); } }
下面是结果:(原件及回文本是不尽相同)为什么???
original text: 12345
cipher: 1483188254174
back to text: 391501310217
你好!非常感谢您帮助我,但是您能否提供一段简单的代码,用于测试您的上述代码。我想要以二进制模式从文件(密钥文件和纯文本文件)中读取的“密钥”和“纯文本”(是否意味着将文件转换为字节?)。但现在我只需要一个示例代码来测试这个类,你能帮助我吗? –
请帮助我如何使用您的代码,我测试了它,但给我很奇怪的结果.... –
我测试了代码,创建了2个分开的RC4对象(用于加密和解密)。解密后的结果与输入相同纯文本=>代码也许很好,但我无法显示密文(在将字节转换为字符串后给了我奇怪的字符),我的意思是如何验证密文是正确(与其他语言的C#或C++实现相比),如何显示密文? –