RC4 encryption java

后端 未结 6 1010
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 05:12

Hi there I am trying to implement the RC4 algorithm in Java. I found this code as an example that help me to understand the idea:

public class RC4 {
  privat         


        
6条回答
  •  情歌与酒
    2020-12-14 05:39

    (I know this is a old thread, but maybe my answer can help who is reading it)

    The problem is not in the RC4 code but in how you are using it. What you have to understand is every time that encript method is invoked, the S array is modified to generate a pseudo random key.

    In this code your are using the decript method after encript over the same instance of RC4 class. But RC4 class have the key creation in the constructor, so when you execute decript method, the key is not recently created as it has been modified by the previous encript. Instead of this code:

    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]);            
    } 
    

    Use a rc4 new instance before decript:

    int[] cipher = rc4.encrypt(text); //encryption      
    System.out.print("\ncipher: ");
    for (int i = 0; i < cipher.length; i++) {          
        System.out.print(cipher[i]);          
    }    
    
    rc4 = new RC4(keytest);
    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]);            
    } 
    

    So the decript method will be have a clean S array, and it will be able to obtain S sequence in the same order than the previous encript method.

提交回复
热议问题