cast5.java

来自「jpeg2000编解码」· Java 代码 · 共 1,317 行 · 第 1/5 页

JAVA
1,317
字号
// $Id: CAST5.java,v 1.1.1.1 2002/08/27 12:32:09 grosbois Exp $//// $Log: CAST5.java,v $// Revision 1.1.1.1  2002/08/27 12:32:09  grosbois// Add cryptix 3.2//// Revision 1.6  2000/08/17 11:40:51  edwin// java.* -> xjava.*//// Revision 1.5  1998/01/21 22:16:18  iang// added URL to RFC-2144.//// Revision 1.4  1997/12/30 11:09:50  raif// *** empty log message ***//// Revision 1.3.1  1997/12/30  raif// + further performance optimisation based on Peter Hjelt//   (MXV) (mxv@iterate.com) tip of unfolding the session//   key arrays into individual native java type objects.//// Revision 1.3  1997/11/29 04:42:55  hopwood// + Changes to engineUpdate method.//// Revision 1.2  1997/11/20 19:31:40  hopwood// + cryptix.util.* name changes.//// Revision 1.1.1.1  1997/11/03 22:36:56  hopwood// + Imported to CVS (tagged as 'start').//// Revision 0.1.1.0  1997/08/18  David Hopwood// + Tightened some of the access specifiers (e.g. SPI methods were public,//   and are now protected).// + Ensured that this class is final, and added a comment that this is for//   security reasons.//   If it were not final, some VMs have a bug that would allow a subclass//   that implements Cloneable to call Object's or Cipher's clone() method//   using invokenonvirtual, which would duplicate the pointer to the native//   state. Then calling finalize() on the original and using the clone (for//   example) would result in freed memory being written to :-(.// + Required native code version is 2.3.//// Revision 0.1.0.1  1997/07/16  David Hopwood// + Cosmetic changes.//// Revision 0.1.0.0  1997/07/15  R. Naffah// + Original version.//// $Endlog$/* * Copyright (c) 1997 Systemics Ltd * on behalf of the Cryptix Development Team.  All rights reserved. */package cryptix.provider.cipher;import cryptix.util.core.Debug;import cryptix.CryptixException;import cryptix.util.core.ArrayUtil;import cryptix.util.core.Hex;import cryptix.provider.key.RawSecretKey;import java.io.PrintWriter;import xjava.security.Cipher;import java.security.Key;import java.security.KeyException;import java.security.Security;import xjava.security.SymmetricCipher;/**  * A subclass of Cipher to implement the CAST5 (a.k.a. CAST-128) algorithm in * Java, as per RFC 2144 dated May 1997. * <p> * In this RFC, Carlisle Adams (the CA in CAST, ST standing for Stafford * Tavares) describes CAST5 as: * <p> * <blockquote> *    "...a DES-like Substitution-Permutation Network (SPN) cryptosystem which *    appears to have good resistance to differential cryptanalysis, linear *    cryptanalysis, and related-key cryptanalysis. This cipher also possesses *    a number of other desirable cryptographic properties, including avalanche, *    Strict Avalanche Criterion (SAC), Bit Independence Criterion (BIC), no *    complementation property, and an absence of weak and semi-weak keys." * </blockquote> * <p> * CAST5 is a symmetric block cipher with a block-size of 8 bytes and * a variable key-size of up to 128 bits. Its authors and their employer * (Entrust Technologies, a Nortel majority-owned company) made it available * worldwide on a royalty-free basis for commercial and non-commercial uses. * <p> * The CAST5 encryption algorithm has been designed to allow a key size * that can vary from 40 bits to 128 bits, in 8-bit increments (that is, the * allowable key sizes are 40, 48, 56, 64, ..., 112, 120, and 128 bits. For * variable keysize operation, the specification is as follows: * <ol> *   <li> For key sizes up to and including 80 bits (i.e., 40, 48, 56, 64, 72, *        and 80 bits), the algorithm is exactly as specified but uses 12 rounds *        instead of 16; *   <li> For key sizes greater than 80 bits, the algorithm uses the full 16 *        rounds; *   <li> For key sizes less than 128 bits, the key is padded with zero bytes *        (in the rightmost, or least significant, positions) out to 128 bits *        (since the CAST5 key schedule assumes an input key of 128 bits). * </ol> * <p> * <b>References:</b> * <ol> *   <li> Carlisle Adams, *        <a href="http://rfc.fh-koeln.de/rfc/html/rfc2144.html"> *        RFC 2144</a>, May 1997. * </ol> * <p> * <b>Copyright</b> &copy; 1997 * <a href="http://www.systemics.com/">Systemics Ltd</a> on behalf of the * <a href="http://www.systemics.com/docs/cryptix/">Cryptix Development Team</a>. * <br>All rights reserved. * <p> * <b>$Revision: 1.1.1.1 $</b> * @author  Raif S. Naffah * @since   Cryptix 2.2.2 */public final class CAST5 // must be final for security reasonsextends Cipherimplements SymmetricCipher{// Debugging methods and vars.//...........................................................................    private static final boolean DEBUG = Debug.GLOBAL_DEBUG;    private static final boolean DEBUG_SLOW = Debug.GLOBAL_DEBUG_SLOW;    private static final int debuglevel = DEBUG ? Debug.getLevel("CAST5") : 0;    private static final PrintWriter err = DEBUG ? Debug.getOutput() : null;    private static void debug(String s) { err.println("CAST5: " + s); }// Native library linking methods and vars.//...........................................................................    private static NativeLink linkStatus = new NativeLink("CAST5", 2, 3);    /**     * Gets an object representing the native linking status of this class.     */    public static cryptix.util.core.LinkStatus getLinkStatus() { return linkStatus; }    /**     * The native reference to the current native key schedule     * structure. Defaults to 0 but is set by native code after a     * successful call to native_init().     * <p>     * IMPORTANT: Do not change the name of this variable without     * duplicating the same in the native code.     */    private long native_cookie;    /**     * This object must be synchronized on while calling any native instance     * method. It is null if the native code is not being used (e.g. the     * library did not load successfully, or the user disabled its use in     * the properties file).     */    private Object native_lock; // defaults to null    private void link() {        synchronized(linkStatus) {            try {                if (linkStatus.attemptLoad()) {                    linkStatus.checkVersion(getLibMajorVersion(), getLibMinorVersion());                    linkStatus.check(native_clinit());                }                if (linkStatus.useNative()) {                    linkStatus.check(native_init());                    native_lock = new Object();                }            } catch (UnsatisfiedLinkError e) {                linkStatus.fail(e);if (DEBUG && debuglevel > 2) debug(e.getMessage());            }if (DEBUG && debuglevel > 2) debug("Using native library? " + (native_lock != null));        }    }// Native support API//...........................................................................    // The methods that get the library version.    private native static int getLibMajorVersion();    private native static int getLibMinorVersion();    /**     * Static initialization and self-test method for the native code.     *     * @return a string if an error occurred or null otherwise.     */    private native String native_clinit();    /**     * Initializes the native state for this cipher object and allocates     * needed native storage for the internal key schedule. A reference     * to the newly allocated space, if successful, is stored in the     * instance variable <code>native_cookie</code>.     *     * @return a string if an error occurred or null otherwise.     */    private native String native_init();    /**     * This function expands the user key to an internal form.     *     * @param  cookie   a valid reference to the native key structure. This     *                  value is set by the native library upon return from     *                  native_init() (see link() method at the top).     * @param  userKey  a byte array representing the user key     * @return an error String, or null if there was no error     */    private native String native_ks(long cookie, byte[] userKey);    /**     * Encrypts/decrypts a data block.     * <p>     * FUTURE: possibly change this to be able to process more than one block,     * to reduce native method call overhead.     * <p>     * SECURITY: the caller <strong>must</strong> ensure that:     * <ul>     *   <li> <code>in != null</code>     *   <li> <code>out != null</code>     *   <li> <code>inOffset >= 0</code>     *   <li> <code>(long)inOffset + BLOCK_LENGTH <= in.length</code>     *   <li> <code>outOffset >= 0</code>     *   <li> <code>(long)outOffset + BLOCK_LENGTH <= out.length</code>     * </ul>     *     * @param  cookie       a valid reference to the native key structure. This     *                      value is set by the native library upon return from     *                      native_init() (see link() method at the top).     * @param  in           input array containing data to encrypt or decrypt     *                      depending on the value of the encrypt boolean parameter.     * @param  inOffset     index of where we should start reading from input.     * @param  out          output array containing data decrypted or encrypted     *                      depending on the value of the encrypt boolean parameter.     * @param  outOffset    index of where we should start writing to output.     * @param  encrypt      if true then encrypt, otherwise decrypt.     * @return the number of bytes crypted (always BLOCK_LENGTH) or 0 if an error     *                      occurred.     */    private native int native_crypt (long cookie, byte[] in, int inOffset,                                     byte[] out, int outOffset, boolean encrypt);    /**     * Finalizes the native state for this object.     *     * @return a string if an error occurred or null otherwise.     */    private native String native_finalize();// Variables and constants//............................................................................    // CAST5 S-boxes    private static final int[]        S1 = {

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?