package kingsy101; import java.math.BigInteger; import java.util.Random; public class Cipher { private BigInteger n; private BigInteger e; private BigInteger d; public Cipher () { BigInteger p = BigInteger.probablePrime (32, new Random ()); BigInteger q = selectPrimeNotEqualTo (p); this.n = p.multiply (q); BigInteger pMinus1qMinus1 = p.subtract (BigInteger.ONE).multiply ( q.subtract (BigInteger.ONE)); this.e = p; while (!e.gcd (pMinus1qMinus1).equals (BigInteger.ONE)) { e = e.add (BigInteger.ONE); } this.d = e.modInverse (pMinus1qMinus1); } private static BigInteger selectPrimeNotEqualTo (BigInteger p) { BigInteger q; do { q = BigInteger.probablePrime (32, new Random ()); } while (p == q); return q; } public byte[] encryptBlock (byte[] myarray) { BigInteger writeBigInt = new BigInteger (myarray); BigInteger encrypt = (writeBigInt.modPow (e, n)); return encrypt.toByteArray (); } public byte[] decryptBlock (byte[] blockData) { BigInteger blockValue = new BigInteger (blockData); BigInteger decrypt = (blockValue.modPow (d, n)); return decrypt.toByteArray (); } } // ------------------ package kingsy101; import static org.junit.Assert.*; import org.junit.Test; public class TestCipher { @Test public void easyValue () { Cipher cipher = new Cipher (); byte[] sourceBlock = { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] encBlock = cipher.encryptBlock (sourceBlock); byte[] decBlock = cipher.decryptBlock (encBlock); assertArrayEquals (sourceBlock, decBlock); } @Test public void easyValueEndingInZero () { Cipher cipher = new Cipher (); byte[] sourceBlock = { 1, 2, 3, 4, 5, 6, 7, 0 }; byte[] encBlock = cipher.encryptBlock (sourceBlock); byte[] decBlock = cipher.decryptBlock (encBlock); assertArrayEquals (sourceBlock, decBlock); } @Test public void easyValueStartingInZero () { Cipher cipher = new Cipher (); byte[] sourceBlock = { 0, 1, 2, 3, 4, 5, 6, 7 }; byte[] encBlock = cipher.encryptBlock (sourceBlock); byte[] decBlock = cipher.decryptBlock (encBlock); assertArrayEquals (new byte[] { 1, 2, 3, 4, 5, 6, 7 }, decBlock); } @Test public void valueExtractedFromRealInput () { Cipher cipher = new Cipher (); byte[] sourceBlock = { 84, 104, 105, 115, 32, 112, 108, 97 }; byte[] encBlock = cipher.encryptBlock (sourceBlock); byte[] decBlock = cipher.decryptBlock (encBlock); assertArrayEquals (sourceBlock, decBlock); } }