Waivio

Recommended Posts

Cipher

1 comment

drago181219962.4 K16 days agoHive.Blog

import java.util.stream.*;

public class Cipher {

    private String key;

    public Cipher() {

        this("aaaaaaaaaa");

    }

    public Cipher(String key) {

        this.key = key;

    }

    public String getKey() {

        return key;

    }

    public String encode(String plainText) {

        return shift(plainText, false);

    }

    public String decode(String cipherText) {

        return shift(cipherText, true);

    }

    private String shift(String plainText, boolean down){

        StringBuilder result = new StringBuilder();

        for(int i=0; i<plainText.length(); i++){

            char currentLett = plainText.charAt(i);

            int transform = (down? -1: 1) * (key.charAt(i% key.length()) - 'a');

            int newTrasf = ((currentLett - 'a' + transform)+26)% 26 + 'a';

            result.append((char) newTrasf);

        }

        return result.toString();

    }

}

Comments

Sort byBest