Writing a simple example of Feistal Cipher

We talk about the Feistal Cipher and implement a simple proof of concept to test the algorithm out.

Computerphile video:
https://www.youtube.com/watch?v=FGhj3CGxl8I

Source code:

package org.ea;

import java.security.MessageDigest;
import java.util.Arrays;

public class FeistelAlg {
    private final static String plainText = "the brown fox jumped over the lazy dog";

    public static void doRound(byte[] left, byte[] right) throws Exception {
        MessageDigest md = MessageDigest.getInstance("sha-1");
        byte[] hash = md.digest(right);

        for (int i = 0; i < left.length; i++) {
            hash[i] = (byte) (left[i] ^ hash[i]);
        }

        for (int j = 0; j < right.length; j++) {
            left[j] = right[j];
        }

        for (int k = 0; k < left.length; k++) {
            right[k] = hash[k];
        }
    }

    public static void switchAround(byte[] left, byte[] right) {
        byte[] hash = new byte[right.length];

        for (int i = 0; i < left.length; i++) {
            hash[i] = left[i];
        }

        for (int j = 0; j < right.length; j++) {
            left[j] = right[j];
        }

        for (int k = 0; k < left.length; k++) {
            right[k] = hash[k];
        }
    }

    public static void main(String[] args) {
        byte[] left;
        byte[] right;

        try {

            left = Arrays.copyOfRange(plainText.getBytes(), 0, plainText.length() / 2);
            right = Arrays.copyOfRange(plainText.getBytes(), plainText.length() / 2, plainText.length());

            for(int i = 0; i < 1234; i++) {
                doRound(left, right);
            }
            switchAround(left, right);

            System.out.println(new String(left));
            System.out.println(new String(right));

            for(int i = 0; i < 1234; i++) {
                doRound(left, right);
            }
            switchAround(left, right);

            System.out.println(new String(left) + new String(right));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.