Java Ascii到字符串解密

时间:2018-09-17 15:55:25

标签: java

Original Question(问题3)

我正在完成一个类的问题,该问题需要将带有键的字符串消息从ascii转换为已解码的字符串消息。我已经尝试了从message.charAt(i)访问字符串,并将其转换为char数组,但是两次都把这个奇怪的东西放到了控制台上。

screenshot of console

这是我运行的方法

public static char[] decrypt(String message) {
    char[] decoded = new char[message.length()];
    char[] newmessage = message.toCharArray();
    int ascii;
    for(int key=0; key<=100; key++) {
        for(int i=0; i<message.length(); i++) {
            ascii = ( (int)newmessage[i] + 127) - 32;
            if(ascii > 126)
                decoded[i] = (char)((int)newmessage[i] - key);
            else
                decoded[i] = (char)((((int)newmessage[i] - key) +127) -32);
        }
    }
    System.out.println(decoded);
    return decoded;
}

这是我在主目录中调用它的地方

    System.out.println("Problem 3");
    String message =  ":mmZ\\dxZmx]Zpgy";
    System.out.println("Message Received: ");
    System.out.println(message);
    decrypt(message);

我似乎无法弄清楚哪里出了问题。预期的输出是每个键将与相应的已解码消息一起打印的结果。第88键将显示消息“黎明时袭击!”。

2 个答案:

答案 0 :(得分:2)

如果您只需要从ASCII解码为Java String,那么正确的方法之一就是

char [] output = StandardCharsets.US_ASCII.decode(ByteBuffer.wrap(input)).array();

根据您的性能要求,您可能需要预分配缓冲区,并且可能是解码器(在上面的示例中,Charset :: decode将动态创建一个)。

答案 1 :(得分:1)

首先要加密,然后才需要对:mmZ\\dxZmx]Zpgy消息进行密钥解码,因此,为了简单起见,请尝试首先使用您的算法对Hey消息进行解码制成,而您忘记了最重要的部分:

if(originalChar + key > 126) then
     EncryptedChar = 32 + ((originalChar + key) - 127)
else
     EncryptedChar = (originalChar + key)

因此,在if语句中,您缺少减号

 if(ascii - key > 126)

总是去重新阅读您的问题。

    for(int key=0; key<=100; key++) {
        for(int i=0; i<message.length(); i++) {
            ascii = ( (int)newmessage[i] + 127) - 32;
            if(ascii - key > 126)
                decoded[i] = (char)((int)newmessage[i] - key);
            else
                decoded[i] = (char)((((int)newmessage[i] - key) +127) -32);
        }
        System.out.println("Decoded with i=" +key +":"+new String(decoded)); // For check what is the correct message. 
    }

扰流器 消息是: 阿塔克在黎明!