如何多次运行加密程序以加强编码?

时间:2014-03-07 17:07:59

标签: loops encryption for-loop decode encode

到目前为止,这是我的代码。我需要运行代码的编码部分5次,然后解码编码相同的次数。我想出了如何对消息进行编码,但现在我无法弄清楚如何通过代码运行“编码”或“解码”变量以加强消息。

public class Codes
    {
        /**
         * Encode and decode a message using a key of values stored in
         * a queue.
         */
        public static void main(String[] args)
        { 
            int[] key = {7, 6, 5, 2, 8, 5, 8, 6, 4, 1};
            Integer keyValue;
            String encoded = "", decoded = "";
            String message = "Queues are useful for encoding messages.";
            Queue<Integer> encodingQueue = new LinkedList<Integer>();
            Queue<Integer> decodingQueue = new LinkedList<Integer>();

            // load key queues 
            for (int scan = 0; scan < key.length; scan++)
            {
                encodingQueue.add(key[scan]);
                decodingQueue.add(key[scan]);
            }

            // encode message
            for (int scan = 0; scan < message.length(); scan++)
            {
                keyValue = encodingQueue.remove();
                encoded += (char) (message.charAt(scan) + keyValue);
                encodingQueue.add(keyValue);
            }

            System.out.println ("Encoded Message:\n" + encoded + "\n");


            // decode message 
            for (int scan = 0; scan < encoded.length(); scan++)
            {
                keyValue = decodingQueue.remove();
                decoded += (char) (encoded.charAt(scan) - keyValue);
                decodingQueue.add(keyValue);
            }

            System.out.println ("Decoded Message:\n" + decoded);
        }


    }

截至目前我正在接收此输出:

Encoded Message:
X{jwmx(gvf'{xgnzt&jpy&jpktlorh'sju{fokw/

Decoded Message:
Queues are useful for encoding messages.

为了完成这个程序,我需要输出看起来像这样:

Encoded Message 1: X{jwmx(gvf'{xgnzt&jpy&jpktlorh'sju{fokw/ 
Encoded Message 2: _?oyu}0mzg.?}iv•|,nq?,orsytuvi.yow?kwq{0 
Encoded Message 3: f?t{}?8s~h5??k~??2rr?2tt{~|{zj5•ty?p•w•1 
Encoded Message 4: m?y}??@y?i<??m???8vs?8yv????~k<?y{?u?}?2 
Encoded Message 5: t?~•??H•?jC??o???>zt?>~x?????lC?~}?z???3 
Decoded Message 5: m?y}??@y?i<??m???8vs?8yv????~k<?y{?u?}?2 
Decoded Message 4: f?t{}?8s~h5??k~??2rr?2tt{~|{zj5•ty?p•w•1 
Decoded Message 3: _?oyu}0mzg.?}iv•|,nq?,orsytuvi.yow?kwq{0 
Decoded Message 2: X{jwmx(gvf'{xgnzt&jpy&jpktlorh'sju{fokw/ 
Decoded Message 1: Queues are useful for encoding messages.

我估计为了实现这一点,我需要使用循环来通过程序运行“编码”和“解码”变量。但是我无法弄清楚如何实现这一目标。

1 个答案:

答案 0 :(得分:1)

如果您为encode()decode()操作使用单独的函数,这会更容易:

class Codes {

  public static void main(String[] args) {
    ...
  }

  private static String encode(String plaintext, Queue<Integer> encodingQueue) {
    ...
  }

  private static String decode(String ciphertext, Queue<Integer> decodingQueue) {
    ...
  }

}

这有帮助吗?