One time pad, encryption and decryption

后端 未结 6 1824
-上瘾入骨i
-上瘾入骨i 2021-01-17 23:34

I am trying to pick up cryptography and had been trying this exercise

Write a program (preferably Java) to generate a one-time pad, which is a relatively large file

6条回答
  •  广开言路
    2021-01-18 00:09

    Here you have a full working example:

        // convert secret text to byte array
        final byte[] secret = "secret".getBytes()
    
        final byte[] encoded = new byte[secret.length];
        final byte[] decoded = new byte[secret.length];
    
        // Generate random key (has to be exchanged)
        final byte[] key = new byte[secret.length];
        new SecureRandom().nextBytes(key);
    
        // Encrypt
        for (int i = 0; i < secret.length; i++) {
            encoded[i] = (byte) (secret[i] ^ key[i]);
        }
    
        // Decrypt
        for (int i = 0; i < encoded.length; i++) {
            decoded[i] = (byte) (encoded[i] ^ key[i]);
        }
    
        assertTrue(Arrays.equals(secret, decoded));
    

提交回复
热议问题