Please help me :(, I am trying this answer in this post Converting string to SecretKey
But it doesn't seem to be working for RC4, please tell me what I am doing wrong. This is my RC4 class in a separate file:
public class RC4 {
SecretKey k;
public RC4() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
KeyGenerator kg = KeyGenerator.getInstance("RC4");
k = kg.generateKey();
}
public byte[] encrypt(final byte[] plaintext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance("RC4"); // Transformation of the algorithm
cipher.init(Cipher.ENCRYPT_MODE, k);
byte[] cipherBytes = cipher.doFinal(plaintext);
return cipherBytes;
}
public byte[] decrypt(final byte[] ciphertext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance("RC4");
cipher.init(Cipher.DECRYPT_MODE, k);
byte[] plainBytes = cipher.doFinal(ciphertext);
return plainBytes;
}
public SecretKey getK() {
return k;
}
public void setK(SecretKey k) {
this.k = k;
}
}
This code below is also from another file in a main method
RC4 rc4Client = new RC4();
SecretKey k = rc4Client.getK();
String encodedK = Base64.getEncoder().encodeToString(k.getEncoded());
//print
System.out.println("Random k: " + k.toString());
byte[] decodedKey = Base64.getDecoder().decode(encodedK);
k = new SecretKeySpec(decodedKey, 0, decodedKey.length, "RC4");
//print
System.out.println("Random k: " + k.toString());
The printed output is:
Random k: javax.crypto.spec.SecretKeySpec@2c97f72b
Random k: javax.crypto.spec.SecretKeySpec@fffe4170
They should be the same, why are they different??