java实现rc4算法代码
时间: 2023-10-05 17:14:32 浏览: 117
以下是Java实现RC4算法的代码:
```java
public class RC4 {
private int[] S = new int[256];
private int[] T = new int[256];
private int keylen;
public RC4(byte[] key) {
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;
int tmp = S[i];
S[i] = S[j];
S[j] = tmp;
}
}
public byte[] encrypt(byte[] plaintext) {
byte[] ciphertext = new byte[plaintext.length];
int i = 0, j = 0;
for (int n = 0; n < plaintext.length; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
int tmp = S[i];
S[i] = S[j];
S[j] = tmp;
int k = S[(S[i] + S[j]) % 256];
ciphertext[n] = (byte) (plaintext[n] ^ k);
}
return ciphertext;
}
public byte[] decrypt(byte[] ciphertext) {
return encrypt(ciphertext);
}
}
```
使用示例:
```java
byte[] key = "secretkey".getBytes();
byte[] data = "Hello, world!".getBytes();
RC4 rc4 = new RC4(key);
byte[] encrypted = rc4.encrypt(data);
byte[] decrypted = rc4.decrypt(encrypted);
System.out.println(new String(data)); // Hello, world!
System.out.println(new String(encrypted)); // VÙ"áÝ*
System.out.println(new String(decrypted)); // Hello, world!
```
阅读全文