How to Do Basic Encryption in Java


The challenge

The most basic encryption method is to map a char to another char by a certain math rule. Because every char has an ASCII value, we can manipulate this value with a simple math expression. For example ‘a’ + 1 would give us ‘b’, because ‘a’ value is 97 and ‘b’ value is 98.

You will need to write a method that does exactly that –

get a string as text and an int as the rule of manipulation, and should return encrypted text. for example:

encrypt(“a”,1) = “b”

Full ascii table is used on our question (256 chars) – so 0-255 are the valid values.

If the value exceeds 255, it should ‘wrap’. ie. if the value is 345 it should wrap to 89.

The solution in Java code

Option 1:

public class BasicEncrypt {
    public String encrypt(String text, int rule) {
        StringBuilder encryped = new StringBuilder();
        for(Character a: text.toCharArray())
            encryped.append(Character.toChars((a+rule)%256)) ;
        return encryped.toString(); 
    }
}

Option 2:

public class BasicEncrypt {
    public String encrypt(String text, int rule) {
       return new String(text.chars().map(i -> (i + rule) % 256).toArray(), 0, text.length());
    }
}

Option 3:

import java.util.stream.Collectors;

public class BasicEncrypt {
    public String encrypt(String text, int rule) {
        StringBuilder result = new StringBuilder();
        text.chars().mapToObj(e-> (char) ((e + rule) % 256)).forEach(e->result.append(e));
        return result.toString();
    }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.util.Random;

public class BasicEncryptTest {

    @Test
    public void testDecrypt() throws Exception {
        BasicEncrypt enc = new BasicEncrypt();
        assertEquals("text = '', rule = 1", "",
                     enc.encrypt("", 1));
        assertEquals("text = 'a', rule = 1", "b",
                     enc.encrypt("a", 1));
        assertEquals("text = 'please encrypt me', rule = 2", "rngcug\"gpet{rv\"og",
                     enc.encrypt("please encrypt me", 2));
    }
    
    @Test
    public void randomTests() throws Exception {
        BasicEncrypt enc = new BasicEncrypt();
        String text;
        int rule;
        for (int i = 0; i < 50; i++) {
            Random r = new Random();
            text = randomString(r.nextInt(40));
            rule = r.nextInt(450);
            assertEquals("text = " + text +" rule = " + rule, solEncrypt(text,rule),
                         enc.encrypt(text, rule));
        }
    }

   private String solEncrypt(String text, int rule) {
        StringBuilder res = new StringBuilder();
        for (Character ch : text.toCharArray()) {
            res.append((char)(ch + rule > 255 ? (ch + rule) % 256 : ch + rule));
        }
        return res.toString();  
    }
    
    private String randomString(int length) {
        Character startChar = 'a';
        Character endChar = 'z';
        return new Random().ints(length, startChar, endChar + 1)
                           .mapToObj(i -> (char) i)
                           .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
                           .toString();
    }
}