Cryptography Reference
In-Depth Information
Finally, here are the enciphering and deciphering methods for the block affine cipher. Each
accepts a message, the block size, and the values of
a
and
b
from the enciphering transfor-
mation
C aP
+
b
.
public static byte[] affineEncipher(byte[] msg,int blockSize,BigInteger a,BigInteger
b) {
//Compute the modulus
BigInteger modulus=BigInteger.valueOf(2).pow(8*blockSize);
//Check the multiplier
if (!(modulus.gcd(a).equals(BigIntegerMath.ONE))) throw new
IllegalArgumentException(“Enciphering key is not relatively prime to the
modulus.”);
byte ba[][]=block(pad(msg,blockSize),blockSize);
//Begin the enciphering
for (int i=0;i<ba.length;i++)
ba[i]=getBytes(a.multiply(new BigInteger(ba[i])).add(b).mod(modulus));
return unBlock(ba,blockSize);
}
public static byte[] affineDecipher(byte[] msg,int blockSize,BigInteger a,BigInteger
b) {
//Compute the modulus
BigInteger modulus=BigInteger.valueOf(2).pow(8*blockSize);
//Check the multiplier
if (!(modulus.gcd(a).equals(BigIntegerMath.ONE))) throw new
IllegalArgumentException(“Enciphering key is not relatively prime to the
modulus.”);
//Compute inverse of a
BigInteger ainv=a.modInverse(modulus);
byte[][] ba=block(msg,blockSize);
//Begin the deciphering
for (int i=0;i<ba.length;i++)
ba[i]=getBytes(BigIntegerMath.lnr(ainv.multiply(new
BigInteger(ba[i]).subtract(b)),modulus));
//Go from blocks to a 1D array, and remove padding; return this
return unPad(unBlock(ba,blockSize),blockSize);
}
This following method is necessary. In order to encipher or decipher, at some point we
convert BigIntegers back into an array of bytes using the toByteArray() method from the
BigInteger class. This method, in addition to returning the binary representation of the Big-
Integer, also returns a sign bit in the high order bit position. This can screw up everything
if the BigInteger already fills up the block; in this case the extra sign bit forces another byte
to be created. When this happens, we must remove the forward byte. This is never a prob-
lem for us, as all of the BigIntegers we use are positive; thus the sign bit is always 0.
Search WWH ::




Custom Search