簡體   English   中英

簡單的加密/解密似乎無法正常工作,請幫助我找到我做錯的事情

[英]Simple encryptio/decryption doesn't seems to work, help me find what i am doing wrong

試圖進行簡單的加密/解密以在簡單的通信協議中使用它。 看來我無法使我的解密方法起作用,或者可能是加密方法,輸出文本不是原始文本。 我究竟做錯了什么?

String s1 = encrypt("Hello World!");
String s2 = decrypt(s1);

public static String encrypt(String decStr) {
        byte[] key = new byte[]{
                92, -33, 70, 90, 42, -22, -76, 38,
                37, 109, 26, -113, 125, 105, 66, 81,
                17, 22, 21, -30, 87, -124, -85, 58,
                40, -116, -100, 28, 37, 127, 51, 36
        };

        byte[] encBytes = decStr.getBytes();

        int n = encBytes.length + 5;
        int k = key[encBytes.length % key.length] & 255;

        for (int i = 0; i < encBytes.length; i++) {
            encBytes[i] ^= key[(n + i) % key.length];
            encBytes[i] ^= key[(k + i) % key.length];
        }

        return new BigInteger(encBytes).toString(36);
}

public static String decrypt(String encStr) {
        byte[] key = new byte[]{
                92, -33, 70, 90, 42, -22, -76, 38,
                37, 109, 26, -113, 125, 105, 66, 81,
                17, 22, 21, -30, 87, -124, -85, 58,
                40, -116, -100, 28, 37, 127, 51, 36
        };

        byte[] encBytes = new BigInteger(encStr, 36).toByteArray();
        byte[] decBytes = Arrays.copyOfRange(encBytes, 1, encBytes.length);

        int n = decBytes.length + 5;
        int k = key[decBytes.length % key.length] & 255;

        for (int i = 0; i < decBytes.length; i++) {
            decBytes[i] ^= key[(n + i) % key.length];
            decBytes[i] ^= key[(k + i) % key.length];
        }

        return new String(decBytes);
}
byte[] decBytes = Arrays.copyOfRange(encBytes, 1, encBytes.length);

您從第二個字符開始。 將1更改為0

byte[] decBytes = Arrays.copyOfRange(encBytes, 0, encBytes.length);

將指定數組的指定范圍復制到新數組中。 范圍的起始索引(從)必須介於零和original.length(含)之間。 original [from]處的值放置在副本的初始元素中(除非from == original.length或from == to)。 來自原始數組中后續元素的值將放入副本中的后續元素中。 范圍(to)的最終索引(必須大於或等於from)可以大於original.length,在這種情況下,(byte)0放置在副本中索引大於或等於的所有元素中到original.length-從。 返回數組的長度為--from。

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOfRange(byte[],%20int,%20int)

另外,您要創建一個新的字節數組,然后立即將其復制到另一個數組中,但切勿使用原始字節數組。 似乎不需要首先執行此復制

測試:

Hello World!
zxj9kxukhtsdmoll41
Hello World!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM