我自己实现了rc4算法,就像加密和解密文本的魅力一样,当我尝试加密/解密图像时出现问题。我的输出图像始终不可读。没有异常被抛出。我不确定它的加密或解密是否有效,或者两者兼而有之。我们将非常感谢您的帮助。
RC4 Class
公共类RC4 {
private byte[] S = new byte[256];
public RC4 (byte[] key) {
byte[] T = new byte[256];
int keylen, j;
byte t;
for (int i = 0; i < 256; i++) {
keylen = key.length;
S[i] = (byte) i;
T[i] = key[i % keylen];
}
//KSA - key-scheduling algorithm is used to initialize the permutation in the array "S"
j = 0;
for (int i = 0 ; i < 256 ; i++)
{
j = ((j + S[i] + T[i]) % 256) & 0xFF;
//swap
t = S[i];
S[i] = S[j];
S[j] = t;
}
}
public byte[] encrypt(byte[] plaintext)
{
int j = 0, i = 0, t, k;
byte temp;
byte[] pt,ct, s;
//deep copy
s = S.clone();
pt = plaintext;
ct = new byte[pt.length];
for (int jj = 0 ; jj < pt.length; jj++)
{
i = ((i + 1) % 256) & 0xFF;
j = ((j + s[i]) % 256) & 0xFF;
//classic swap
temp = s[jj];
s[jj] = s[j];
s[j] = temp;
t = ((s[i] + s[j]) % 256) & 0xFF;
k = s[t];
ct[jj] = (byte) (k ^ pt[jj]);
}
return ct;
}
public byte[] decrypt(byte[] ciphertext)
{
return encrypt(ciphertext);
}
}
然后我的电话: 服务器端
Bitmap SelectedImage = BitmapFactory.decodeFile(selectedImagePath);
byte[] b = bitmapToByteArray(SelectedImage);
RC4 rc4 = new RC4(sharedSecret);
byte[] encrypted = rc4.encrypt(b);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeObject(encrypted);
objectOutputStream.flush();
客户端
FileOutputStream fos = null;
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
byte[] b = (byte[])objectInputStream.readObject();
RC4 rc4 = new RC4(sharedSecret);
byte[] decrypted = rc4.decrypt(b);
Bitmap bmp = BitmapFactory.decodeByteArray(decrypted, 0, decrypted.length);
fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
答案 0 :(得分:0)
我发现了我的错误,它在加密功能中;滥用柜台。以下是更正后的代码。
for (int counter = 0 ; counter < pt.length; counter++)
{
i = ((i + 1) % 256) & 0xFF;
j = ((j + s[i]) % 256) & 0xFF;
//classic swap
temp = s[j];
s[j] = s[i];
s[i] = temp;
t = ((s[i] + s[j]) % 256) & 0xFF;
k = s[t];
ct[counter] = (byte) (k ^ pt[counter]);