📄 cipher.java
字号:
/* Cipher.java -- Interface to a cryptographic cipher. Copyright (C) 2004 Free Software Foundation, Inc.This file is part of GNU Classpath.GNU Classpath is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2, or (at your option)any later version.GNU Classpath is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with GNU Classpath; see the file COPYING. If not, write to theFree Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA02110-1301 USA.Linking this library statically or dynamically with other modules ismaking a combined work based on this library. Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule. An independent module is a module which is not derived fromor based on this library. If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so. If you do not wish to do so, delete thisexception statement from your version. */package javax.crypto;import gnu.java.security.Engine;import java.security.AlgorithmParameters;import java.security.InvalidAlgorithmParameterException;import java.security.InvalidKeyException;import java.security.Key;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.security.Provider;import java.security.SecureRandom;import java.security.Security;import java.security.cert.Certificate;import java.security.cert.X509Certificate;import java.security.spec.AlgorithmParameterSpec;import java.util.StringTokenizer;/** * <p>This class implements a cryptographic cipher for transforming * data.</p> * * <p>Ciphers cannot be instantiated directly; rather one of the * <code>getInstance</code> must be used to instantiate a given * <i>transformation</i>, optionally with a specific provider.</p> * * <p>A transformation is of the form:</p> * * <ul> * <li><i>algorithm</i>/<i>mode</i>/<i>padding</i>, or</li> * <li><i>algorithm</i> * </ul> * * <p>where <i>algorithm</i> is the base name of a cryptographic cipher * (such as "AES"), <i>mode</i> is the abbreviated name of a block * cipher mode (such as "CBC" for cipher block chaining mode), and * <i>padding</i> is the name of a padding scheme (such as * "PKCS5Padding"). If only the algorithm name is supplied, then the * provider-specific default mode and padding will be used.</p> * * <p>An example transformation is:</p> * * <blockquote><code>Cipher c = * Cipher.getInstance("AES/CBC/PKCS5Padding");</code></blockquote> * * <p>Finally, when requesting a block cipher in stream cipher mode * (such as <acronym title="Advanced Encryption Standard">AES</acronym> * in OFB or CFB mode) the number of bits to be processed * at a time may be specified by appending it to the name of the mode; * e.g. <code>"AES/OFB8/NoPadding"</code>. If no such number is * specified a provider-specific default value is used.</p> * * @author Casey Marshall (csm@gnu.org) * @see java.security.KeyGenerator * @see javax.crypto.SecretKey */public class Cipher{ // Constants and variables. // ------------------------------------------------------------------------ private static final String SERVICE = "Cipher"; /** * The decryption operation mode. */ public static final int DECRYPT_MODE = 2; /** * The encryption operation mode. */ public static final int ENCRYPT_MODE = 1; /** * Constant for when the key to be unwrapped is a private key. */ public static final int PRIVATE_KEY = 2; /** * Constant for when the key to be unwrapped is a public key. */ public static final int PUBLIC_KEY = 1; /** * Constant for when the key to be unwrapped is a secret key. */ public static final int SECRET_KEY = 3; /** * The key unwrapping operation mode. */ public static final int UNWRAP_MODE = 4; /** * The key wrapping operation mode. */ public static final int WRAP_MODE = 3; /** * The uninitialized state. This state signals that any of the * <code>init</code> methods have not been called, and therefore no * transformations can be done. */ private static final int INITIAL_STATE = 0; /** The underlying cipher service provider interface. */ private CipherSpi cipherSpi; /** The provider from which this instance came. */ private Provider provider; /** The transformation requested. */ private String transformation; /** Our current state (encrypting, wrapping, etc.) */ private int state; // Class methods. // ------------------------------------------------------------------------ /** * <p>Creates a new cipher instance for the given transformation.</p> * * <p>The installed providers are tried in order for an * implementation, and the first appropriate instance is returned. If * no installed provider can provide the implementation, an * appropriate exception is thrown.</p> * * @param transformation The transformation to create. * @return An appropriate cipher for this transformation. * @throws java.security.NoSuchAlgorithmException If no installed * provider can supply the appropriate cipher or mode. * @throws javax.crypto.NoSuchPaddingException If no installed * provider can supply the appropriate padding. */ public static final Cipher getInstance(String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException { Provider[] providers = Security.getProviders(); NoSuchPaddingException ex = null; String msg = ""; for (int i = 0; i < providers.length; i++) { try { return getInstance(transformation, providers[i]); } catch (NoSuchAlgorithmException nsae) { msg = nsae.getMessage(); ex = null; } catch (NoSuchPaddingException nspe) { ex = nspe; } } if (ex != null) { throw ex; } throw new NoSuchAlgorithmException(msg); } /** * <p>Creates a new cipher instance for the given transformation and * the named provider.</p> * * @param transformation The transformation to create. * @param provider The name of the provider to use. * @return An appropriate cipher for this transformation. * @throws java.security.NoSuchAlgorithmException If the provider cannot * supply the appropriate cipher or mode. * @throws java.security.NoSuchProviderException If the named provider * is not installed. * @throws javax.crypto.NoSuchPaddingException If the provider cannot * supply the appropriate padding. */ public static final Cipher getInstance(String transformation, String provider) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException { Provider p = Security.getProvider(provider); if (p == null) { throw new NoSuchProviderException(provider); } return getInstance(transformation, p); } /** * Creates a new cipher instance for the given transform and the given * provider. * * @param transformation The transformation to create. * @param provider The provider to use. * @return An appropriate cipher for this transformation. * @throws java.security.NoSuchAlgorithmException If the given * provider cannot supply the appropriate cipher or mode. * @throws javax.crypto.NoSuchPaddingException If the given * provider cannot supply the appropriate padding scheme. */ public static final Cipher getInstance(String transformation, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException { CipherSpi result = null; String key = null; String alg = null, mode = null, pad = null; String msg = ""; if (transformation.indexOf('/') < 0) { try { result = (CipherSpi) Engine.getInstance(SERVICE, transformation, provider); return new Cipher(result, provider, transformation); } catch (Exception e) { msg = e.getMessage(); } } else { StringTokenizer tok = new StringTokenizer(transformation, "/"); if (tok.countTokens() != 3) { throw new NoSuchAlgorithmException("badly formed transformation"); } alg = tok.nextToken(); mode = tok.nextToken(); pad = tok.nextToken(); try { result = (CipherSpi) Engine.getInstance(SERVICE, transformation, provider); return new Cipher(result, provider, transformation); } catch (Exception e) { msg = e.getMessage(); } try { result = (CipherSpi) Engine.getInstance(SERVICE, alg + '/' + mode, provider); result.engineSetPadding(pad); return new Cipher(result, provider, transformation); } catch (Exception e) { if (e instanceof NoSuchPaddingException) { throw (NoSuchPaddingException) e; } msg = e.getMessage(); } try { result = (CipherSpi) Engine.getInstance(SERVICE, alg + "//" + pad, provider); result.engineSetMode(mode); return new Cipher(result, provider, transformation); } catch (Exception e) { msg = e.getMessage(); } try { result = (CipherSpi) Engine.getInstance(SERVICE, alg, provider); result.engineSetMode(mode); result.engineSetPadding(pad); return new Cipher(result, provider, transformation); } catch (Exception e) { if (e instanceof NoSuchPaddingException) { throw (NoSuchPaddingException) e; } msg = e.getMessage(); } } throw new NoSuchAlgorithmException(transformation + ": " + msg); }// Constructor. // ------------------------------------------------------------------------ /** * Create a cipher. * * @param cipherSpi The underlying implementation of the cipher. * @param provider The provider of this cipher implementation. * @param transformation The transformation this cipher performs. */ protected Cipher(CipherSpi cipherSpi, Provider provider, String transformation) { this.cipherSpi = cipherSpi; this.provider = provider; this.transformation = transformation; state = INITIAL_STATE; }// Public instance methods. // ------------------------------------------------------------------------ /** * Get the name that this cipher instance was created with; this is * equivalent to the "transformation" argument given to any of the * {@link #getInstance()} methods. * * @return The cipher name. */ public final String getAlgorithm() { return transformation; } /** * Return the size of blocks, in bytes, that this cipher processes. * * @return The block size. */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -