0

我有一个

String X = 0110100001100101011011000110110001101111530940929e959001f70dd4da5f5cc3b373165781

我首先通过 X.getBytes() 将字符串 X 变成一个字节 [];我使用这个进行RC4加密..

public static byte[] RC4(byte[] x,byte[] keyBytes)   
{   
    byte[] e = null; 

    try   
    {   
        SecureRandom sr = new SecureRandom(keyBytes);
        KeyGenerator kg = KeyGenerator.getInstance(algorithm);
        kg.init(sr);
        SecretKey sk = kg.generateKey();  
        Cipher enCipher = Cipher.getInstance("RC4");   
        enCipher.init(Cipher.ENCRYPT_MODE,sk);   
        e = enCipher.doFinal(plaintext);              
    }   
    catch(Exception ex)   
    {   
        ex.printStackTrace();   
    }   
    return e;   
} 

编辑** 加密后我使用cipher = encrpyted.toString(); 这返回我的值cipher = [B@a1c582

之后我尝试使用 RC4 运行解密,并使用 toString 函数尝试取回上面列出的字符串 X 的原始值,但无济于事..

我做了什么..编辑**

//the reason i send using string is due to me having a client server architecture restriction on buffered writer, and this is the receiving side

            message = stdIn.readLine();
            System.out.println("Message received : " + message);

            byte [] kc = key.getBytes();
            byte [] decrypt = message.getBytes();
            byte [] decryptC = EncryptionScheme.decrypt(decrypt, kc);
            X = new String(decryptC);
            System.out.println("String X = " + X);

Message received : [B@a1c582

String X = ����,��

有没有办法解决这个问题?我想取回字符串String X = 0110100001100101011011000110110001101111530940929e959001f70dd4da5f5cc3b373165781

decryption algorithm

    public static byte[] decrypt(byte[] ciphertext,byte[] keyBytes)   
    {   
        byte de[] = null;   
        try   
        {   
            SecureRandom sr = new SecureRandom(keyBytes);
            KeyGenerator kg = KeyGenerator.getInstance(algorithm);
            kg.init(sr);
            SecretKey sk = kg.generateKey();    
            Cipher deCipher = Cipher.getInstance("RC4");   
            deCipher.init(Cipher.DECRYPT_MODE,sk);   
            de = deCipher.doFinal(ciphertext);   
        }   
        catch(Exception e)   
        {   
            e.printStackTrace();   
        }    
        return de;   

    }  
4

2 回答 2

0

加密后我使用cipher = encrpyted.toString()

这是无效的。所有这些给你的是调用的结果Object.toString(),它是对象类(byte[]编码为[B)和它的组合System.identityHashCode()。如果这是您通过网络发送的内容,这是我可以从您的帖子中得出的唯一结论,那么您不可能正确解密它,因为它首先不包含密文。

由于String不是二进制数据的容器,因此您必须发送密文的 base-64 或 base-16 或 base-36 编码,在接收器处对其进行解码,然后对其进行解密。

于 2015-08-02T05:22:09.290 回答
0

如果您找不到更好的解决方案,您可以执行以下操作

    StringBuilder s = new StringBuilder();
    for(byte b : arr) {
        s.append(Integer.toBinaryString(0x100 | 0xFF & b).substring(1, 9));
    }
于 2015-08-02T04:33:29.003 回答