The Data Encryption Standard. DES is a 64-bit block cipher with a 56-bit * key, developed by IBM in the 1970's for the standardization process begun by * the National Bureau of Standards (now NIST).
* *New applications should not use DES except for compatibility.
* *This version is based upon the description and sample implementation in * [1].
* *References:
*Adjust the parity for a raw key array. This essentially means that each * byte in the array will have an odd number of '1' bits (the last bit in * each byte is unused.
* * @param kb The key array, to be parity-adjusted. * @param offset The starting index into the key bytes. */ public static void adjustParity(byte[] kb, int offset) { for (int i = offset; i < KEY_SIZE; i++) { kb[i] ^= (PARITY[kb[i] & 0xff] == 8) ? 1 : 0; } } /** *Test if a byte array, which must be at least 8 bytes long, is parity * adjusted.
* * @param kb The key bytes. * @param offset The starting index into the key bytes. * @returntrue
if the first 8 bytes of kb have been
* parity adjusted. false
otherwise.
*/
public static boolean isParityAdjusted(byte[] kb, int offset) {
int w = 0x88888888;
int n = PARITY[kb[offset+0] & 0xff]; n <<= 4;
n |= PARITY[kb[offset+1] & 0xff]; n <<= 4;
n |= PARITY[kb[offset+2] & 0xff]; n <<= 4;
n |= PARITY[kb[offset+3] & 0xff]; n <<= 4;
n |= PARITY[kb[offset+4] & 0xff]; n <<= 4;
n |= PARITY[kb[offset+5] & 0xff]; n <<= 4;
n |= PARITY[kb[offset+6] & 0xff]; n <<= 4;
n |= PARITY[kb[offset+7] & 0xff];
return (n & w) == 0;
}
/**
* Test if a key is a weak key.
* * @param kb The key to test. * @returntrue
if the key is weak.
*/
public static boolean isWeak(byte[] kb) {
// return Arrays.equals(kb, WEAK_KEYS[0]) || Arrays.equals(kb, WEAK_KEYS[1])
// || Arrays.equals(kb, WEAK_KEYS[2]) || Arrays.equals(kb, WEAK_KEYS[3])
// || Arrays.equals(kb, WEAK_KEYS[4]) || Arrays.equals(kb, WEAK_KEYS[5])
// || Arrays.equals(kb, WEAK_KEYS[6]) || Arrays.equals(kb, WEAK_KEYS[7]);
for (int i = 0; i < WEAK_KEYS.length; i++) {
if (Arrays.equals(WEAK_KEYS[i], kb)) {
return true;
}
}
return false;
}
/**
* Test if a key is a semi-weak key.
* * @param kb The key to test. * @returntrue
if this key is semi-weak.
*/
public static boolean isSemiWeak(byte[] kb) {
// return Arrays.equals(kb, SEMIWEAK_KEYS[0])
// || Arrays.equals(kb, SEMIWEAK_KEYS[1])
// || Arrays.equals(kb, SEMIWEAK_KEYS[2])
// || Arrays.equals(kb, SEMIWEAK_KEYS[3])
// || Arrays.equals(kb, SEMIWEAK_KEYS[4])
// || Arrays.equals(kb, SEMIWEAK_KEYS[5])
// || Arrays.equals(kb, SEMIWEAK_KEYS[6])
// || Arrays.equals(kb, SEMIWEAK_KEYS[7])
// || Arrays.equals(kb, SEMIWEAK_KEYS[8])
// || Arrays.equals(kb, SEMIWEAK_KEYS[9])
// || Arrays.equals(kb, SEMIWEAK_KEYS[10])
// || Arrays.equals(kb, SEMIWEAK_KEYS[11]);
for (int i = 0; i < SEMIWEAK_KEYS.length; i++) {
if (Arrays.equals(SEMIWEAK_KEYS[i], kb)) {
return true;
}
}
return false;
}
/**
* Test if the designated byte array represents a possibly weak key.
* * @param kb the byte array to test. * @returntrue
if kb
represents a possibly weak key.
* Returns false
otherwise.
*/
public static boolean isPossibleWeak(byte[] kb) {
for (int i = 0; i < POSSIBLE_WEAK_KEYS.length; i++) {
if (Arrays.equals(POSSIBLE_WEAK_KEYS[i], kb)) {
return true;
}
}
return false;
}
/**
* The core DES function. This is used for both encryption and decryption, * the only difference being the key.
* * @param in The input bytes. * @param i The starting offset into the input bytes. * @param out The output bytes. * @param o The starting offset into the output bytes. * @param key The working key. */ private static void desFunc(byte[] in, int i, byte[] out, int o, int[] key) { int right, left, work; // Load. left = (in[i++] & 0xff) << 24 | (in[i++] & 0xff) << 16 | (in[i++] & 0xff) << 8 | in[i++] & 0xff; right = (in[i++] & 0xff) << 24 | (in[i++] & 0xff) << 16 | (in[i++] & 0xff) << 8 | in[i ] & 0xff; // Initial permutation. work = ((left >>> 4) ^ right) & 0x0F0F0F0F; left ^= work << 4; right ^= work; work = ((left >>> 16) ^ right) & 0x0000FFFF; left ^= work << 16; right ^= work; work = ((right >>> 2) ^ left) & 0x33333333; right ^= work << 2; left ^= work; work = ((right >>> 8) ^ left) & 0x00FF00FF; right ^= work << 8; left ^= work; right = ((right << 1) | ((right >>> 31) & 1)) & 0xFFFFFFFF; work = (left ^ right) & 0xAAAAAAAA; left ^= work; right ^= work; left = ((left << 1) | ((left >>> 31) & 1)) & 0xFFFFFFFF; int k = 0, t; for (int round = 0; round < 8; round++) { work = right >>> 4 | right << 28; work ^= key[k++]; t = SP7[work & 0x3F]; work >>>= 8; t |= SP5[work & 0x3F]; work >>>= 8; t |= SP3[work & 0x3F]; work >>>= 8; t |= SP1[work & 0x3F]; work = right ^ key[k++]; t |= SP8[work & 0x3F]; work >>>= 8; t |= SP6[work & 0x3F]; work >>>= 8; t |= SP4[work & 0x3F]; work >>>= 8; t |= SP2[work & 0x3F]; left ^= t; work = left >>> 4 | left << 28; work ^= key[k++]; t = SP7[work & 0x3F]; work >>>= 8; t |= SP5[work & 0x3F]; work >>>= 8; t |= SP3[work & 0x3F]; work >>>= 8; t |= SP1[work & 0x3F]; work = left ^ key[k++]; t |= SP8[work & 0x3F]; work >>>= 8; t |= SP6[work & 0x3F]; work >>>= 8; t |= SP4[work & 0x3F]; work >>>= 8; t |= SP2[work & 0x3F]; right ^= t; } // The final permutation. right = (right << 31) | (right >>> 1); work = (left ^ right) & 0xAAAAAAAA; left ^= work; right ^= work; left = (left << 31) | (left >>> 1); work = ((left >>> 8) ^ right) & 0x00FF00FF; left ^= work << 8; right ^= work; work = ((left >>> 2) ^ right) & 0x33333333; left ^= work << 2; right ^= work; work = ((right >>> 16) ^ left) & 0x0000FFFF; right ^= work << 16; left ^= work; work = ((right >>> 4) ^ left) & 0x0F0F0F0F; right ^= work << 4; left ^= work; out[o++] = (byte)(right >>> 24); out[o++] = (byte)(right >>> 16); out[o++] = (byte)(right >>> 8); out[o++] = (byte) right; out[o++] = (byte)(left >>> 24); out[o++] = (byte)(left >>> 16); out[o++] = (byte)(left >>> 8); out[o ] = (byte) left; } // Instance methods implementing BaseCipher // ------------------------------------------------------------------------- public Object clone() { return new DES(); } public Iterator blockSizes() { return Collections.singleton(new Integer(BLOCK_SIZE)).iterator(); } public Iterator keySizes() { return Collections.singleton(new Integer(KEY_SIZE)).iterator(); } public Object makeKey(byte[] kb, int bs) throws InvalidKeyException { if (kb == null || kb.length != KEY_SIZE) throw new InvalidKeyException("DES keys must be 8 bytes long"); // if (Properties.checkForWeakKeys() // && (isWeak(kb) || isSemiWeak(kb) || isPossibleWeak(kb))) { // throw new WeakKeyException(); // } int i, j, l, m, n; long pc1m = 0, pcr = 0; for (i = 0; i < 56; i++) { l = PC1[i]; pc1m |= ((kb[l >>> 3] & (0x80 >>> (l & 7))) != 0) ? (1L << (55 - i)) : 0; } Context ctx = new Context(); // Encryption key first. for (i = 0; i < 16; i++) { pcr = 0; m = i << 1; n = m + 1; for (j = 0; j < 28; j++) { l = j + ROTARS[i]; if (l < 28) pcr |= ((pc1m & 1L << (55 - l)) != 0) ? (1L << (55 - j)) : 0; else pcr |= ((pc1m & 1L << (55 - (l - 28))) != 0) ? (1L << (55 - j)) : 0; } for (j = 28; j < 56; j++) { l = j + ROTARS[i]; if (l < 56) pcr |= ((pc1m & 1L << (55 - l)) != 0) ? (1L << (55 - j)) : 0; else pcr |= ((pc1m & 1L << (55 - (l - 28))) != 0) ? (1L << (55 - j)) : 0; } for (j = 0; j < 24; j++) { if ((pcr & 1L << (55 - PC2[j ])) != 0) ctx.ek[m] |= 1 << (23 - j); if ((pcr & 1L << (55 - PC2[j+24])) != 0) ctx.ek[n] |= 1 << (23 - j); } } // The decryption key is the same, but in reversed order. for (i = 0; i < Context.EXPANDED_KEY_SIZE; i += 2) { ctx.dk[30 - i] = ctx.ek[i]; ctx.dk[31 - i] = ctx.ek[i+1]; } // "Cook" the keys. for (i = 0; i < 32; i += 2) { int x, y; x = ctx.ek[i ]; y = ctx.ek[i+1]; ctx.ek[i ] = ((x & 0x00FC0000) << 6) | ((x & 0x00000FC0) << 10) | ((y & 0x00FC0000) >>> 10) | ((y & 0x00000FC0) >>> 6); ctx.ek[i+1] = ((x & 0x0003F000) << 12) | ((x & 0x0000003F) << 16) | ((y & 0x0003F000) >>> 4) | (y & 0x0000003F); x = ctx.dk[i ]; y = ctx.dk[i+1]; ctx.dk[i ] = ((x & 0x00FC0000) << 6) | ((x & 0x00000FC0) << 10) | ((y & 0x00FC0000) >>> 10) | ((y & 0x00000FC0) >>> 6); ctx.dk[i+1] = ((x & 0x0003F000) << 12) | ((x & 0x0000003F) << 16) | ((y & 0x0003F000) >>> 4) | (y & 0x0000003F); } return ctx; } public void encrypt(byte[] in, int i, byte[] out, int o, Object K, int bs) { desFunc(in, i, out, o, ((Context) K).ek); } public void decrypt(byte[] in, int i, byte[] out, int o, Object K, int bs) { desFunc(in, i, out, o, ((Context) K).dk); } // Inner classe(s) /** * Simple wrapper class around the session keys. Package-private so TripleDES * can see it. */ final class Context { // Constants and variables // ---------------------------------------------------------------------- private static final int EXPANDED_KEY_SIZE = 32; /** The encryption key. */ int[] ek; /** The decryption key. */ int[] dk; // Constructor(s) // ---------------------------------------------------------------------- /** Default 0-arguments constructor. */ Context() { ek = new int[EXPANDED_KEY_SIZE]; dk = new int[EXPANDED_KEY_SIZE]; } // Class methods // ---------------------------------------------------------------------- // Instance methods // ---------------------------------------------------------------------- byte[] getEncryptionKeyBytes() { return toByteArray(ek); } byte[] getDecryptionKeyBytes() { return toByteArray(dk); } byte[] toByteArray(int[] k) { byte[] result = new byte[4 * k.length]; for (int i = 0, j = 0; i < k.length; i++) { result[j++] = (byte)(k[i] >>> 24); result[j++] = (byte)(k[i] >>> 16); result[j++] = (byte)(k[i] >>> 8); result[j++] = (byte) k[i]; } return result; } } } /** *A collection of utility methods used throughout this project.
* * @version $Revision: 1.10 $ */ class Util { // Constants and variables // ------------------------------------------------------------------------- // Hex charset private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray(); // Base-64 charset private static final String BASE64_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./"; private static final char[] BASE64_CHARSET = BASE64_CHARS.toCharArray(); // Constructor(s) // ------------------------------------------------------------------------- /** Trivial constructor to enforce Singleton pattern. */ private Util() { super(); } // Class methods // ------------------------------------------------------------------------- /** *Returns a string of hexadecimal digits from a byte array. Each byte is * converted to 2 hex symbols; zero(es) included.
* *This method calls the method with same name and three arguments as:
* ** toString(ba, 0, ba.length); ** * @param ba the byte array to convert. * @return a string of hexadecimal characters (two for each byte) * representing the designated input byte array. */ public static String toString(byte[] ba) { return toString(ba, 0, ba.length); } /** *
Returns a string of hexadecimal digits from a byte array, starting at
* offset
and consisting of length
bytes. Each byte
* is converted to 2 hex symbols; zero(es) included.
Returns a string of hexadecimal digits from a byte array. Each byte is * converted to 2 hex symbols; zero(es) included. The argument is * treated as a large little-endian integer and is returned as a * large big-endian integer.
* *This method calls the method with same name and three arguments as:
* ** toReversedString(ba, 0, ba.length); ** * @param ba the byte array to convert. * @return a string of hexadecimal characters (two for each byte) * representing the designated input byte array. */ public static String toReversedString(byte[] ba) { return toReversedString(ba, 0, ba.length); } /** *
Returns a string of hexadecimal digits from a byte array, starting at
* offset
and consisting of length
bytes. Each byte
* is converted to 2 hex symbols; zero(es) included.
The byte array is treated as a large little-endian integer, and * is returned as a large big-endian integer.
* * @param ba the byte array to convert. * @param offset the index from which to start considering the bytes to * convert. * @param length the count of bytes, starting from the designated offset to * convert. * @return a string of hexadecimal characters (two for each byte) * representing the designated input byte sub-array. */ public static final String toReversedString(byte[] ba, int offset, int length) { char[] buf = new char[length * 2]; for (int i = offset+length-1, j = 0, k; i >= offset; ) { k = ba[offset + i--]; buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F]; buf[j++] = HEX_DIGITS[ k & 0x0F]; } return new String(buf); } /** *Returns a byte array from a string of hexadecimal digits.
* * @param s a string of hexadecimal ASCII characters * @return the decoded byte array from the input hexadecimal string. */ public static byte[] toBytesFromString(String s) { int limit = s.length(); byte[] result = new byte[((limit + 1) / 2)]; int i = 0, j = 0; if ((limit % 2) == 1) { result[j++] = (byte) fromDigit(s.charAt(i++)); } while (i < limit) { result[j ] = (byte) (fromDigit(s.charAt(i++)) << 4); result[j++] |= (byte) fromDigit(s.charAt(i++)); } return result; } /** *Returns a byte array from a string of hexadecimal digits, interpreting * them as a large big-endian integer and returning it as a large * little-endian integer.
* * @param s a string of hexadecimal ASCII characters * @return the decoded byte array from the input hexadecimal string. */ public static byte[] toReversedBytesFromString(String s) { int limit = s.length(); byte[] result = new byte[((limit + 1) / 2)]; int i = 0; if ((limit % 2) == 1) { result[i++] = (byte) fromDigit(s.charAt(--limit)); } while (limit > 0) { result[i ] = (byte) fromDigit(s.charAt(--limit)); result[i++] |= (byte) (fromDigit(s.charAt(--limit)) << 4); } return result; } /** *Returns a number from 0
to 15
corresponding
* to the designated hexadecimal digit.
Returns a string of 8 hexadecimal digits (most significant digit first)
* corresponding to the unsigned integer n
.
Returns a string of hexadecimal digits from an integer array. Each int * is converted to 4 hex symbols.
*/ public static String toString(int[] ia) { int length = ia.length; char[] buf = new char[length * 8]; for (int i = 0, j = 0, k; i < length; i++) { k = ia[i]; buf[j++] = HEX_DIGITS[(k >>> 28) & 0x0F]; buf[j++] = HEX_DIGITS[(k >>> 24) & 0x0F]; buf[j++] = HEX_DIGITS[(k >>> 20) & 0x0F]; buf[j++] = HEX_DIGITS[(k >>> 16) & 0x0F]; buf[j++] = HEX_DIGITS[(k >>> 12) & 0x0F]; buf[j++] = HEX_DIGITS[(k >>> 8) & 0x0F]; buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F]; buf[j++] = HEX_DIGITS[ k & 0x0F]; } return new String(buf); } /** *Returns a string of 16 hexadecimal digits (most significant digit first)
* corresponding to the unsigned long n
.
Similar to the toString()
method except that the Unicode
* escape character is inserted before every pair of bytes. Useful to
* externalise byte arrays that will be constructed later from such strings;
* eg. s-box values.
Similar to the toString()
method except that the Unicode
* escape character is inserted before every pair of bytes. Useful to
* externalise byte arrays that will be constructed later from such strings;
* eg. s-box values.
Similar to the toString()
method except that the Unicode
* escape character is inserted before every pair of bytes. Useful to
* externalise integer arrays that will be constructed later from such
* strings; eg. s-box values.
Dumps a byte array as a string, in a format that is easy to read for
* debugging. The string m
is prepended to the start of each
* line.
If offset
and length
are omitted, the whole
* array is used. If m
is omitted, nothing is prepended to each
* line.
Returns a string of 2 hexadecimal digits (most significant digit first)
* corresponding to the lowest 8 bits of n
.
Converts a designated byte array to a Base-64 representation, with the * exceptions that (a) leading 0-byte(s) are ignored, and (b) the character * '.' (dot) shall be used instead of "+' (plus).
* *Used by SASL password file manipulation primitives.
* * @param buffer an arbitrary sequence of bytes to represent in Base-64. * @return unpadded (without the '=' character(s)) Base-64 representation of * the input. */ public static final String toBase64(byte[] buffer) { int len = buffer.length, pos = len % 3; byte b0 = 0, b1 = 0, b2 = 0; switch (pos) { case 1: b2 = buffer[0]; break; case 2: b1 = buffer[0]; b2 = buffer[1]; break; } StringBuffer sb = new StringBuffer(); int c; boolean notleading = false; do { c = (b0 & 0xFC) >>> 2; if (notleading || c != 0) { sb.append(BASE64_CHARSET[c]); notleading = true; } c = ((b0 & 0x03) << 4) | ((b1 & 0xF0) >>> 4); if (notleading || c != 0) { sb.append(BASE64_CHARSET[c]); notleading = true; } c = ((b1 & 0x0F) << 2) | ((b2 & 0xC0) >>> 6); if (notleading || c != 0) { sb.append(BASE64_CHARSET[c]); notleading = true; } c = b2 & 0x3F; if (notleading || c != 0) { sb.append(BASE64_CHARSET[c]); notleading = true; } if (pos >= len) { break; } else { try { b0 = buffer[pos++]; b1 = buffer[pos++]; b2 = buffer[pos++]; } catch (ArrayIndexOutOfBoundsException x) { break; } } } while (true); if (notleading) { return sb.toString(); } return "0"; } /** *The inverse function of the above.
* *Converts a string representing the encoding of some bytes in Base-64 * to their original form.
* * @param str the Base-64 encoded representation of some byte(s). * @return the bytes represented by thestr
.
* @throws NumberFormatException if str
is null
, or
* str
contains an illegal Base-64 character.
* @see #toBase64(byte[])
*/
public static final byte[] fromBase64(String str) {
int len = str.length();
if (len == 0) {
throw new NumberFormatException("Empty string");
}
byte[] a = new byte[len + 1];
int i, j;
for (i = 0; i < len; i++) {
try {
a[i] = (byte) BASE64_CHARS.indexOf(str.charAt(i));
} catch (ArrayIndexOutOfBoundsException x) {
throw new NumberFormatException("Illegal character at #"+i);
}
}
i = len - 1;
j = len;
try {
while (true) {
a[j] = a[i];
if (--i < 0) {
break;
}
a[j] |= (a[i] & 0x03) << 6;
j--;
a[j] = (byte)((a[i] & 0x3C) >>> 2);
if (--i < 0) {
break;
}
a[j] |= (a[i] & 0x0F) << 4;
j--;
a[j] = (byte)((a[i] & 0x30) >>> 4);
if (--i < 0) {
break;
}
a[j] |= (a[i] << 2);
j--;
a[j] = 0;
if (--i < 0) {
break;
}
}
} catch (Exception ignored) {
}
try { // ignore leading 0-bytes
while(a[j] == 0) {
j++;
}
} catch (Exception x) {
return new byte[1]; // one 0-byte
}
byte[] result = new byte[len - j + 1];
System.arraycopy(a, j, result, 0, len - j + 1);
return result;
}
// BigInteger utilities ----------------------------------------------------
/**
* Treats the input as the MSB representation of a number, and discards * leading zero elements. For efficiency, the input is simply returned if no * leading zeroes are found.
* * @param n the {@link BigInteger} to trim. * @return the byte array representation of the designated {@link BigInteger} * with no leading 0-bytes. */ public static final byte[] trim(BigInteger n) { byte[] in = n.toByteArray(); if (in.length == 0 || in[0] != 0) { return in; } int len = in.length; int i = 1; while (in[i] == 0 && i < len) { ++i; } byte[] result = new byte[len - i]; System.arraycopy(in, i, result, 0, len - i); return result; } /** *Returns a hexadecimal dump of the trimmed bytes of a {@link BigInteger}. *
* * @param x the {@link BigInteger} to display. * @return the string representation of the designated {@link BigInteger}. */ public static final String dump(BigInteger x) { return dumpString(trim(x)); } } /** *A basic abstract class to facilitate implementing symmetric key block * ciphers.
* * @version $Revision: 1.10 $ */ abstract class BaseCipher implements IBlockCipher, IBlockCipherSpi { // Constants and variables // ------------------------------------------------------------------------- /** The canonical name prefix of the cipher. */ protected String name; /** The default block size, in bytes. */ protected int defaultBlockSize; /** The default key size, in bytes. */ protected int defaultKeySize; /** The current block size, in bytes. */ protected int currentBlockSize; /** The session key for this instance. */ protected transient Object currentKey; /** The instance lock. */ protected Object lock = new Object(); // Constructor(s) // ------------------------------------------------------------------------- /** *Trivial constructor for use by concrete subclasses.
* * @param name the canonical name prefix of this instance. * @param defaultBlockSize the default block size in bytes. * @param defaultKeySize the default key size in bytes. */ protected BaseCipher(String name, int defaultBlockSize, int defaultKeySize) { super(); this.name = name; this.defaultBlockSize = defaultBlockSize; this.defaultKeySize = defaultKeySize; } // Class methods // ------------------------------------------------------------------------- // Instance methods // ------------------------------------------------------------------------- // IBlockCipher interface implementation ----------------------------------- public abstract Object clone(); public String name() { StringBuffer sb = new StringBuffer(name).append('-'); if (currentKey == null) { sb.append(String.valueOf(8*defaultBlockSize)); } else { sb.append(String.valueOf(8*currentBlockSize)); } return sb.toString(); } public int defaultBlockSize() { return defaultBlockSize; } public int defaultKeySize() { return defaultKeySize; } public void init(Map attributes) throws InvalidKeyException { synchronized(lock) { if (currentKey != null) { throw new IllegalStateException(); } Integer bs = (Integer) attributes.get(CIPHER_BLOCK_SIZE); if (bs == null) { // no block size was specified. if (currentBlockSize == 0) { // happy birthday currentBlockSize = defaultBlockSize; } // else it's a clone. use as is } else { currentBlockSize = bs.intValue(); // ensure that value is valid Iterator it; boolean ok = false; for (it = blockSizes(); it.hasNext(); ) { ok = (currentBlockSize == ((Integer) it.next()).intValue()); if (ok) { break; } } if (!ok) { throw new IllegalArgumentException(IBlockCipher.CIPHER_BLOCK_SIZE); } } byte[] k = (byte[]) attributes.get(KEY_MATERIAL); currentKey = makeKey(k, currentBlockSize); } } public int currentBlockSize() { if (currentKey == null) { throw new IllegalStateException(); } return currentBlockSize; } public void reset() { synchronized(lock) { // currentBlockSize = 0; currentKey = null; } } public void encryptBlock(byte[] in, int inOffset, byte[] out, int outOffset) throws IllegalStateException { synchronized(lock) { if (currentKey == null) { throw new IllegalStateException(); } encrypt(in, inOffset, out, outOffset, currentKey, currentBlockSize); } } public void decryptBlock(byte[] in, int inOffset, byte[] out, int outOffset) throws IllegalStateException { synchronized(lock) { if (currentKey == null) { throw new IllegalStateException(); } decrypt(in, inOffset, out, outOffset, currentKey, currentBlockSize); } } public boolean selfTest() { int ks; Iterator bit; // do symmetry tests for all block-size/key-size combos for (Iterator kit = keySizes(); kit.hasNext(); ) { ks = ((Integer) kit.next()).intValue(); for (bit = blockSizes(); bit.hasNext(); ) { if (!testSymmetry(ks, ((Integer) bit.next()).intValue())) { return false; } } } return true; } // own methods ------------------------------------------------------------- private boolean testSymmetry(int ks, int bs) { try { byte[] kb = new byte[ks]; byte[] pt = new byte[bs]; byte[] ct = new byte[bs]; byte[] cpt = new byte[bs]; int i; for (i = 0; i < ks; i++) { kb[i] = (byte) i; } for (i = 0; i < bs; i++) { pt[i] = (byte) i; } Object k = makeKey(kb, bs); encrypt(pt, 0, ct, 0, k, bs); decrypt(ct, 0, cpt, 0, k, bs); return Arrays.equals(pt, cpt); } catch (Exception x) { x.printStackTrace(System.err); return false; } } protected boolean testKat(byte[] kb, byte[] ct) { return testKat(kb, ct, new byte[ct.length]); // all-zero plaintext } protected boolean testKat(byte[] kb, byte[] ct, byte[] pt) { try { int bs = pt.length; byte[] t = new byte[bs]; Object k = makeKey(kb, bs); // test encryption encrypt(pt, 0, t, 0, k, bs); if (!Arrays.equals(t, ct)) { return false; } // test decryption decrypt(t, 0, t, 0, k, bs); return Arrays.equals(t, pt); } catch (Exception x) { x.printStackTrace(System.err); return false; } } } /** *Package-private interface exposing mandatory methods to be implemented by * concrete {@link gnu.crypto.cipher.BaseCipher} sub-classes.
* * @version $Revision: 1.4 $ */ interface IBlockCipherSpi extends Cloneable { // Constants // ------------------------------------------------------------------------- // Methods // ------------------------------------------------------------------------- /** *Returns an {@link java.util.Iterator} over the supported block sizes. * Each element returned by this object is a {@link java.lang.Integer}.
* * @return anIterator
over the supported block sizes.
*/
Iterator blockSizes();
/**
* Returns an {@link java.util.Iterator} over the supported key sizes. * Each element returned by this object is a {@link java.lang.Integer}.
* * @return anIterator
over the supported key sizes.
*/
Iterator keySizes();
/**
* Expands a user-supplied key material into a session key for a * designated block size.
* * @param k the user-supplied key material. * @param bs the desired block size in bytes. * @return an Object encapsulating the session key. * @exception IllegalArgumentException if the block size is invalid. * @exception InvalidKeyException if the key data is invalid. */ Object makeKey(byte[]k, int bs) throws InvalidKeyException; /** *Encrypts exactly one block of plaintext.
* * @param in the plaintext. * @param inOffset index ofin
from which to start considering
* data.
* @param out the ciphertext.
* @param outOffset index of out
from which to store the result.
* @param k the session key to use.
* @param bs the block size to use.
* @exception IllegalArgumentException if the block size is invalid.
* @exception ArrayIndexOutOfBoundsException if there is not enough room in
* either the plaintext or ciphertext buffers.
*/
void
encrypt(byte[] in, int inOffset, byte[] out, int outOffset, Object k, int bs);
/**
* Decrypts exactly one block of ciphertext.
* * @param in the ciphertext. * @param inOffset index ofin
from which to start considering
* data.
* @param out the plaintext.
* @param outOffset index of out
from which to store the result.
* @param k the session key to use.
* @param bs the block size to use.
* @exception IllegalArgumentException if the block size is invalid.
* @exception ArrayIndexOutOfBoundsException if there is not enough room in
* either the plaintext or ciphertext buffers.
*/
void
decrypt(byte[] in, int inOffset, byte[] out, int outOffset, Object k, int bs);
/**
* A correctness test that consists of basic symmetric encryption / * decryption test(s) for all supported block and key sizes, as well as one * (1) variable key Known Answer Test (KAT).
* * @returntrue
if the implementation passes simple
* correctness tests. Returns false
otherwise.
*/
boolean selfTest();
}
/**
* The basic visible methods of any symmetric key block cipher.
* *A symmetric key block cipher is a function that maps n-bit plaintext * blocks to n-bit ciphertext blocks; n being the cipher's block size. * This encryption function is parameterised by a k-bit key, and is invertible. * Its inverse is the decryption function.
* *Possible initialisation values for an instance of this type are:
* *reset()
is invoked on the instance. Furthermore, the size of
* this key material shall be taken as an indication on the key size in which
* to operate this instance.IMPLEMENTATION NOTE: Although all the concrete classes in this * package implement the {@link Cloneable} interface, it is important to note * here that such an operation DOES NOT clone any session key material * that may have been used in initialising the source cipher (the instance to be * cloned). Instead a clone of an already initialised cipher is another instance * that operates with the same block size but without any knowledge of * neither key material nor key size.
* * @version $Revision: 1.7 $ */ interface IBlockCipher extends Cloneable { // Constants // ------------------------------------------------------------------------- /** *Property name of the block size in which to operate a block cipher. * The value associated with this property name is taken to be an * {@link Integer}.
*/ String CIPHER_BLOCK_SIZE = "gnu.crypto.cipher.block.size"; /** *Property name of the user-supplied key material. The value associated * to this property name is taken to be a byte array.
*/ String KEY_MATERIAL = "gnu.crypto.cipher.key.material"; // Methods // ------------------------------------------------------------------------- /** *Returns the canonical name of this instance.
* * @return the canonical name of this instance. */ String name(); /** *Returns the default value, in bytes, of the algorithm's block size.
* * @return the default value, in bytes, of the algorithm's block size. */ int defaultBlockSize(); /** *Returns the default value, in bytes, of the algorithm's key size.
* * @return the default value, in bytes, of the algorithm's key size. */ int defaultKeySize(); /** *Returns an {@link Iterator} over the supported block sizes. Each * element returned by this object is an {@link Integer}.
* * @return an {@link Iterator} over the supported block sizes. */ Iterator blockSizes(); /** *Returns an {@link Iterator} over the supported key sizes. Each element * returned by this object is an {@link Integer}.
* * @return an {@link Iterator} over the supported key sizes. */ Iterator keySizes(); /** *Returns a clone of this instance.
* * @return a clone copy of this instance. */ Object clone(); /** *Initialises the algorithm with designated attributes. Permissible names * and values are described in the class documentation above.
* * @param attributes a set of name-value pairs that describes the desired * future behaviour of this instance. * @exception InvalidKeyException if the key data is invalid. * @exception IllegalStateException if the instance is already initialised. * @see #KEY_MATERIAL * @see #CIPHER_BLOCK_SIZE */ void init(Map attributes) throws InvalidKeyException, IllegalStateException; /** *Returns the currently set block size for this instance.
* * @return the current block size for this instance. * @exception IllegalStateException if the instance is not initialised. */ int currentBlockSize() throws IllegalStateException; /** *Resets the algorithm instance for re-initialisation and use with other * characteristics. This method always succeeds.
*/ void reset(); /** *Encrypts exactly one block of plaintext.
* * @param in the plaintext. * @param inOffset index ofin
from which to start considering
* data.
* @param out the ciphertext.
* @param outOffset index of out
from which to store result.
* @exception IllegalStateException if the instance is not initialised.
*/
void encryptBlock(byte[] in, int inOffset, byte[] out, int outOffset)
throws IllegalStateException;
/**
* Decrypts exactly one block of ciphertext.
* * @param in the plaintext. * @param inOffset index ofin
from which to start considering
* data.
* @param out the ciphertext.
* @param outOffset index of out
from which to store result.
* @exception IllegalStateException if the instance is not initialised.
*/
void decryptBlock(byte[] in, int inOffset, byte[] out, int outOffset)
throws IllegalStateException;
/**
* A correctness test that consists of basic symmetric encryption / * decryption test(s) for all supported block and key sizes, as well as one * (1) variable key Known Answer Test (KAT).
* * @returntrue
if the implementation passes simple
* correctness tests. Returns false
otherwise.
*/
boolean selfTest();
}