Method from javax.crypto.Cipher Detail: |
void chooseFirstProvider() {
if (spi != null) {
return;
}
synchronized (lock) {
if (spi != null) {
return;
}
if (debug != null) {
int w = --warnCount;
if (w >= 0) {
debug.println("Cipher.init() not first method "
+ "called, disabling delayed provider selection");
if (w == 0) {
debug.println("Further warnings of this type will "
+ "be suppressed");
}
new Exception("Call trace").printStackTrace();
}
}
Exception lastException = null;
while ((firstService != null) || serviceIterator.hasNext()) {
Service s;
CipherSpi thisSpi;
if (firstService != null) {
s = firstService;
thisSpi = firstSpi;
firstService = null;
firstSpi = null;
} else {
s = (Service)serviceIterator.next();
thisSpi = null;
}
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
Transform tr = getTransform(s, transforms);
if (tr == null) {
// should never happen
continue;
}
if (tr.supportsModePadding(s) == S_NO) {
continue;
}
try {
if (thisSpi == null) {
Object obj = s.newInstance(null);
if (obj instanceof CipherSpi == false) {
continue;
}
thisSpi = (CipherSpi)obj;
}
tr.setModePadding(thisSpi);
initCryptoPermission();
spi = thisSpi;
provider = s.getProvider();
// not needed any more
firstService = null;
serviceIterator = null;
transforms = null;
return;
} catch (Exception e) {
lastException = e;
}
}
ProviderException e = new ProviderException
("Could not construct CipherSpi instance");
if (lastException != null) {
e.initCause(lastException);
}
throw e;
}
}
Choose the Spi from the first provider available. Used if
delayed provider selection is not possible because init()
is not the first method called. |
public final byte[] doFinal() throws IllegalBlockSizeException, BadPaddingException {
checkCipherState();
chooseFirstProvider();
return spi.engineDoFinal(null, 0, 0);
}
Finishes a multiple-part encryption or decryption operation, depending
on how this cipher was initialized.
Input data that may have been buffered during a previous
update operation is processed, with padding (if requested)
being applied.
If an AEAD mode such as GCM/CCM is being used, the authentication
tag is appended in the case of encryption, or verified in the
case of decryption.
The result is stored in a new buffer.
Upon finishing, this method resets this cipher object to the state
it was in when previously initialized via a call to init .
That is, the object is reset and available to encrypt or decrypt
(depending on the operation mode that was specified in the call to
init ) more data.
Note: if any exception is thrown, this cipher object may need to
be reset before it can be used again. |
public final byte[] doFinal(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
checkCipherState();
// Input sanity check
if (input == null) {
throw new IllegalArgumentException("Null input buffer");
}
chooseFirstProvider();
return spi.engineDoFinal(input, 0, input.length);
}
Encrypts or decrypts data in a single-part operation, or finishes a
multiple-part operation. The data is encrypted or decrypted,
depending on how this cipher was initialized.
The bytes in the input buffer, and any input bytes that
may have been buffered during a previous update operation,
are processed, with padding (if requested) being applied.
If an AEAD mode such as GCM/CCM is being used, the authentication
tag is appended in the case of encryption, or verified in the
case of decryption.
The result is stored in a new buffer.
Upon finishing, this method resets this cipher object to the state
it was in when previously initialized via a call to init .
That is, the object is reset and available to encrypt or decrypt
(depending on the operation mode that was specified in the call to
init ) more data.
Note: if any exception is thrown, this cipher object may need to
be reset before it can be used again. |
public final int doFinal(byte[] output,
int outputOffset) throws IllegalBlockSizeException, ShortBufferException, BadPaddingException {
checkCipherState();
// Input sanity check
if ((output == null) || (outputOffset < 0)) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
return spi.engineDoFinal(null, 0, 0, output, outputOffset);
}
Finishes a multiple-part encryption or decryption operation, depending
on how this cipher was initialized.
Input data that may have been buffered during a previous
update operation is processed, with padding (if requested)
being applied.
If an AEAD mode such as GCM/CCM is being used, the authentication
tag is appended in the case of encryption, or verified in the
case of decryption.
The result is stored in the output buffer, starting at
outputOffset inclusive.
If the output buffer is too small to hold the result,
a ShortBufferException is thrown. In this case, repeat this
call with a larger output buffer. Use
getOutputSize to determine how big
the output buffer should be.
Upon finishing, this method resets this cipher object to the state
it was in when previously initialized via a call to init .
That is, the object is reset and available to encrypt or decrypt
(depending on the operation mode that was specified in the call to
init ) more data.
Note: if any exception is thrown, this cipher object may need to
be reset before it can be used again. |
public final int doFinal(ByteBuffer input,
ByteBuffer output) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
checkCipherState();
if ((input == null) || (output == null)) {
throw new IllegalArgumentException("Buffers must not be null");
}
if (input == output) {
throw new IllegalArgumentException("Input and output buffers must "
+ "not be the same object, consider using buffer.duplicate()");
}
if (output.isReadOnly()) {
throw new ReadOnlyBufferException();
}
chooseFirstProvider();
return spi.engineDoFinal(input, output);
}
Encrypts or decrypts data in a single-part operation, or finishes a
multiple-part operation. The data is encrypted or decrypted,
depending on how this cipher was initialized.
All input.remaining() bytes starting at
input.position() are processed.
If an AEAD mode such as GCM/CCM is being used, the authentication
tag is appended in the case of encryption, or verified in the
case of decryption.
The result is stored in the output buffer.
Upon return, the input buffer's position will be equal
to its limit; its limit will not have changed. The output buffer's
position will have advanced by n, where n is the value returned
by this method; the output buffer's limit will not have changed.
If output.remaining() bytes are insufficient to
hold the result, a ShortBufferException is thrown.
In this case, repeat this call with a larger output buffer. Use
getOutputSize to determine how big
the output buffer should be.
Upon finishing, this method resets this cipher object to the state
it was in when previously initialized via a call to init .
That is, the object is reset and available to encrypt or decrypt
(depending on the operation mode that was specified in the call to
init ) more data.
Note: if any exception is thrown, this cipher object may need to
be reset before it can be used again.
Note: this method should be copy-safe, which means the
input and output buffers can reference
the same byte array and no unprocessed input data is overwritten
when the result is copied into the output buffer. |
public final byte[] doFinal(byte[] input,
int inputOffset,
int inputLen) throws IllegalBlockSizeException, BadPaddingException {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
return spi.engineDoFinal(input, inputOffset, inputLen);
}
Encrypts or decrypts data in a single-part operation, or finishes a
multiple-part operation. The data is encrypted or decrypted,
depending on how this cipher was initialized.
The first inputLen bytes in the input
buffer, starting at inputOffset inclusive, and any input
bytes that may have been buffered during a previous update
operation, are processed, with padding (if requested) being applied.
If an AEAD mode such as GCM/CCM is being used, the authentication
tag is appended in the case of encryption, or verified in the
case of decryption.
The result is stored in a new buffer.
Upon finishing, this method resets this cipher object to the state
it was in when previously initialized via a call to init .
That is, the object is reset and available to encrypt or decrypt
(depending on the operation mode that was specified in the call to
init ) more data.
Note: if any exception is thrown, this cipher object may need to
be reset before it can be used again. |
public final int doFinal(byte[] input,
int inputOffset,
int inputLen,
byte[] output) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
return spi.engineDoFinal(input, inputOffset, inputLen,
output, 0);
}
Encrypts or decrypts data in a single-part operation, or finishes a
multiple-part operation. The data is encrypted or decrypted,
depending on how this cipher was initialized.
The first inputLen bytes in the input
buffer, starting at inputOffset inclusive, and any input
bytes that may have been buffered during a previous update
operation, are processed, with padding (if requested) being applied.
If an AEAD mode such as GCM/CCM is being used, the authentication
tag is appended in the case of encryption, or verified in the
case of decryption.
The result is stored in the output buffer.
If the output buffer is too small to hold the result,
a ShortBufferException is thrown. In this case, repeat this
call with a larger output buffer. Use
getOutputSize to determine how big
the output buffer should be.
Upon finishing, this method resets this cipher object to the state
it was in when previously initialized via a call to init .
That is, the object is reset and available to encrypt or decrypt
(depending on the operation mode that was specified in the call to
init ) more data.
Note: if any exception is thrown, this cipher object may need to
be reset before it can be used again.
Note: this method should be copy-safe, which means the
input and output buffers can reference
the same byte array and no unprocessed input data is overwritten
when the result is copied into the output buffer. |
public final int doFinal(byte[] input,
int inputOffset,
int inputLen,
byte[] output,
int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0
|| outputOffset < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
return spi.engineDoFinal(input, inputOffset, inputLen,
output, outputOffset);
}
Encrypts or decrypts data in a single-part operation, or finishes a
multiple-part operation. The data is encrypted or decrypted,
depending on how this cipher was initialized.
The first inputLen bytes in the input
buffer, starting at inputOffset inclusive, and any input
bytes that may have been buffered during a previous
update operation, are processed, with padding
(if requested) being applied.
If an AEAD mode such as GCM/CCM is being used, the authentication
tag is appended in the case of encryption, or verified in the
case of decryption.
The result is stored in the output buffer, starting at
outputOffset inclusive.
If the output buffer is too small to hold the result,
a ShortBufferException is thrown. In this case, repeat this
call with a larger output buffer. Use
getOutputSize to determine how big
the output buffer should be.
Upon finishing, this method resets this cipher object to the state
it was in when previously initialized via a call to init .
That is, the object is reset and available to encrypt or decrypt
(depending on the operation mode that was specified in the call to
init ) more data.
Note: if any exception is thrown, this cipher object may need to
be reset before it can be used again.
Note: this method should be copy-safe, which means the
input and output buffers can reference
the same byte array and no unprocessed input data is overwritten
when the result is copied into the output buffer. |
public final String getAlgorithm() {
return this.transformation;
}
Returns the algorithm name of this Cipher object.
This is the same name that was specified in one of the
getInstance calls that created this Cipher
object.. |
public final int getBlockSize() {
chooseFirstProvider();
return spi.engineGetBlockSize();
}
Returns the block size (in bytes). |
public final ExemptionMechanism getExemptionMechanism() {
chooseFirstProvider();
return exmech;
}
Returns the exemption mechanism object used with this cipher. |
public final byte[] getIV() {
chooseFirstProvider();
return spi.engineGetIV();
}
Returns the initialization vector (IV) in a new buffer.
This is useful in the case where a random IV was created,
or in the context of password-based encryption or
decryption, where the IV is derived from a user-supplied password. |
public static final Cipher getInstance(String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException {
List transforms = getTransforms(transformation);
List cipherServices = new ArrayList(transforms.size());
for (Iterator t = transforms.iterator(); t.hasNext(); ) {
Transform transform = (Transform)t.next();
cipherServices.add(new ServiceId("Cipher", transform.transform));
}
List services = GetInstance.getServices(cipherServices);
// make sure there is at least one service from a signed provider
// and that it can use the specified mode and padding
Iterator t = services.iterator();
Exception failure = null;
while (t.hasNext()) {
Service s = (Service)t.next();
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
Transform tr = getTransform(s, transforms);
if (tr == null) {
// should never happen
continue;
}
int canuse = tr.supportsModePadding(s);
if (canuse == S_NO) {
// does not support mode or padding we need, ignore
continue;
}
if (canuse == S_YES) {
return new Cipher(null, s, t, transformation, transforms);
} else { // S_MAYBE, try out if it works
try {
CipherSpi spi = (CipherSpi)s.newInstance(null);
tr.setModePadding(spi);
return new Cipher(spi, s, t, transformation, transforms);
} catch (Exception e) {
failure = e;
}
}
}
throw new NoSuchAlgorithmException
("Cannot find any provider supporting " + transformation, failure);
}
Returns a Cipher object that implements the specified
transformation.
This method traverses the list of registered security Providers,
starting with the most preferred Provider.
A new Cipher object encapsulating the
CipherSpi implementation from the first
Provider that supports the specified algorithm is returned.
Note that the list of registered providers may be retrieved via
the Security.getProviders() method. |
public static final Cipher getInstance(String transformation,
String provider) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException {
if ((provider == null) || (provider.length() == 0)) {
throw new IllegalArgumentException("Missing provider");
}
Provider p = Security.getProvider(provider);
if (p == null) {
throw new NoSuchProviderException("No such provider: " +
provider);
}
return getInstance(transformation, p);
}
Returns a Cipher object that implements the specified
transformation.
A new Cipher object encapsulating the
CipherSpi implementation from the specified provider
is returned. The specified provider must be registered
in the security provider list.
Note that the list of registered providers may be retrieved via
the Security.getProviders() method. |
public static final Cipher getInstance(String transformation,
Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException {
if (provider == null) {
throw new IllegalArgumentException("Missing provider");
}
Exception failure = null;
List transforms = getTransforms(transformation);
boolean providerChecked = false;
String paddingError = null;
for (Iterator t = transforms.iterator(); t.hasNext();) {
Transform tr = (Transform)t.next();
Service s = provider.getService("Cipher", tr.transform);
if (s == null) {
continue;
}
if (providerChecked == false) {
// for compatibility, first do the lookup and then verify
// the provider. this makes the difference between a NSAE
// and a SecurityException if the
// provider does not support the algorithm.
Exception ve = JceSecurity.getVerificationResult(provider);
if (ve != null) {
String msg = "JCE cannot authenticate the provider "
+ provider.getName();
throw new SecurityException(msg, ve);
}
providerChecked = true;
}
if (tr.supportsMode(s) == S_NO) {
continue;
}
if (tr.supportsPadding(s) == S_NO) {
paddingError = tr.pad;
continue;
}
try {
CipherSpi spi = (CipherSpi)s.newInstance(null);
tr.setModePadding(spi);
Cipher cipher = new Cipher(spi, transformation);
cipher.provider = s.getProvider();
cipher.initCryptoPermission();
return cipher;
} catch (Exception e) {
failure = e;
}
}
// throw NoSuchPaddingException if the problem is with padding
if (failure instanceof NoSuchPaddingException) {
throw (NoSuchPaddingException)failure;
}
if (paddingError != null) {
throw new NoSuchPaddingException
("Padding not supported: " + paddingError);
}
throw new NoSuchAlgorithmException
("No such algorithm: " + transformation, failure);
}
Returns a Cipher object that implements the specified
transformation.
A new Cipher object encapsulating the
CipherSpi implementation from the specified Provider
object is returned. Note that the specified Provider object
does not have to be registered in the provider list. |
public static final int getMaxAllowedKeyLength(String transformation) throws NoSuchAlgorithmException {
CryptoPermission cp = getConfiguredPermission(transformation);
return cp.getMaxKeySize();
}
Returns the maximum key length for the specified transformation
according to the installed JCE jurisdiction policy files. If
JCE unlimited strength jurisdiction policy files are installed,
Integer.MAX_VALUE will be returned.
For more information on default key size in JCE jurisdiction
policy files, please see Appendix E in the
Java Cryptography Architecture Reference Guide. |
public static final AlgorithmParameterSpec getMaxAllowedParameterSpec(String transformation) throws NoSuchAlgorithmException {
CryptoPermission cp = getConfiguredPermission(transformation);
return cp.getAlgorithmParameterSpec();
}
Returns an AlgorithmParameterSpec object which contains
the maximum cipher parameter value according to the
jurisdiction policy file. If JCE unlimited strength jurisdiction
policy files are installed or there is no maximum limit on the
parameters for the specified transformation in the policy file,
null will be returned. |
public final int getOutputSize(int inputLen) {
if (!initialized && !(this instanceof NullCipher)) {
throw new IllegalStateException("Cipher not initialized");
}
if (inputLen < 0) {
throw new IllegalArgumentException("Input size must be equal " +
"to or greater than zero");
}
chooseFirstProvider();
return spi.engineGetOutputSize(inputLen);
}
Returns the length in bytes that an output buffer would need to be in
order to hold the result of the next update or
doFinal operation, given the input length
inputLen (in bytes).
This call takes into account any unprocessed (buffered) data from a
previous update call, padding, and AEAD tagging.
The actual output length of the next update or
doFinal call may be smaller than the length returned by
this method. |
public final AlgorithmParameters getParameters() {
chooseFirstProvider();
return spi.engineGetParameters();
}
Returns the parameters used with this cipher.
The returned parameters may be the same that were used to initialize
this cipher, or may contain a combination of default and random
parameter values used by the underlying cipher implementation if this
cipher requires algorithm parameters but was not initialized with any. |
public final Provider getProvider() {
chooseFirstProvider();
return this.provider;
}
Returns the provider of this Cipher object. |
public final void init(int opmode,
Key key) throws InvalidKeyException {
init(opmode, key, JceSecurity.RANDOM);
}
Initializes this cipher with a key.
The cipher is initialized for one of the following four operations:
encryption, decryption, key wrapping or key unwrapping, depending
on the value of opmode .
If this cipher requires any algorithm parameters that cannot be
derived from the given key , the underlying cipher
implementation is supposed to generate the required parameters itself
(using provider-specific default or random values) if it is being
initialized for encryption or key wrapping, and raise an
InvalidKeyException if it is being
initialized for decryption or key unwrapping.
The generated parameters can be retrieved using
getParameters or
getIV (if the parameter is an IV).
If this cipher requires algorithm parameters that cannot be
derived from the input parameters, and there are no reasonable
provider-specific default values, initialization will
necessarily fail.
If this cipher (including its underlying feedback or padding scheme)
requires any random bytes (e.g., for parameter generation), it will get
them using the SecureRandom
implementation of the highest-priority
installed provider as the source of randomness.
(If none of the installed providers supply an implementation of
SecureRandom, a system-provided source of randomness will be used.)
Note that when a Cipher object is initialized, it loses all
previously-acquired state. In other words, initializing a Cipher is
equivalent to creating a new instance of that Cipher and initializing
it. |
public final void init(int opmode,
Certificate certificate) throws InvalidKeyException {
init(opmode, certificate, JceSecurity.RANDOM);
}
Initializes this cipher with the public key from the given certificate.
The cipher is initialized for one of the following four operations:
encryption, decryption, key wrapping or key unwrapping, depending
on the value of opmode .
If the certificate is of type X.509 and has a key usage
extension field marked as critical, and the value of the key usage
extension field implies that the public key in
the certificate and its corresponding private key are not
supposed to be used for the operation represented by the value
of opmode ,
an InvalidKeyException
is thrown.
If this cipher requires any algorithm parameters that cannot be
derived from the public key in the given certificate, the underlying
cipher
implementation is supposed to generate the required parameters itself
(using provider-specific default or random values) if it is being
initialized for encryption or key wrapping, and raise an
InvalidKeyException if it is being initialized for decryption or
key unwrapping.
The generated parameters can be retrieved using
getParameters or
getIV (if the parameter is an IV).
If this cipher requires algorithm parameters that cannot be
derived from the input parameters, and there are no reasonable
provider-specific default values, initialization will
necessarily fail.
If this cipher (including its underlying feedback or padding scheme)
requires any random bytes (e.g., for parameter generation), it will get
them using the
SecureRandom
implementation of the highest-priority
installed provider as the source of randomness.
(If none of the installed providers supply an implementation of
SecureRandom, a system-provided source of randomness will be used.)
Note that when a Cipher object is initialized, it loses all
previously-acquired state. In other words, initializing a Cipher is
equivalent to creating a new instance of that Cipher and initializing
it. |
public final void init(int opmode,
Key key,
SecureRandom random) throws InvalidKeyException {
initialized = false;
checkOpmode(opmode);
if (spi != null) {
checkCryptoPerm(spi, key);
spi.engineInit(opmode, key, random);
} else {
try {
chooseProvider(I_KEY, opmode, key, null, null, random);
} catch (InvalidAlgorithmParameterException e) {
// should never occur
throw new InvalidKeyException(e);
}
}
initialized = true;
this.opmode = opmode;
}
Initializes this cipher with a key and a source of randomness.
The cipher is initialized for one of the following four operations:
encryption, decryption, key wrapping or key unwrapping, depending
on the value of opmode .
If this cipher requires any algorithm parameters that cannot be
derived from the given key , the underlying cipher
implementation is supposed to generate the required parameters itself
(using provider-specific default or random values) if it is being
initialized for encryption or key wrapping, and raise an
InvalidKeyException if it is being
initialized for decryption or key unwrapping.
The generated parameters can be retrieved using
getParameters or
getIV (if the parameter is an IV).
If this cipher requires algorithm parameters that cannot be
derived from the input parameters, and there are no reasonable
provider-specific default values, initialization will
necessarily fail.
If this cipher (including its underlying feedback or padding scheme)
requires any random bytes (e.g., for parameter generation), it will get
them from random .
Note that when a Cipher object is initialized, it loses all
previously-acquired state. In other words, initializing a Cipher is
equivalent to creating a new instance of that Cipher and initializing
it. |
public final void init(int opmode,
Key key,
AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
init(opmode, key, params, JceSecurity.RANDOM);
}
Initializes this cipher with a key and a set of algorithm
parameters.
The cipher is initialized for one of the following four operations:
encryption, decryption, key wrapping or key unwrapping, depending
on the value of opmode .
If this cipher requires any algorithm parameters and
params is null, the underlying cipher implementation is
supposed to generate the required parameters itself (using
provider-specific default or random values) if it is being
initialized for encryption or key wrapping, and raise an
InvalidAlgorithmParameterException if it is being
initialized for decryption or key unwrapping.
The generated parameters can be retrieved using
getParameters or
getIV (if the parameter is an IV).
If this cipher requires algorithm parameters that cannot be
derived from the input parameters, and there are no reasonable
provider-specific default values, initialization will
necessarily fail.
If this cipher (including its underlying feedback or padding scheme)
requires any random bytes (e.g., for parameter generation), it will get
them using the SecureRandom
implementation of the highest-priority
installed provider as the source of randomness.
(If none of the installed providers supply an implementation of
SecureRandom, a system-provided source of randomness will be used.)
Note that when a Cipher object is initialized, it loses all
previously-acquired state. In other words, initializing a Cipher is
equivalent to creating a new instance of that Cipher and initializing
it. |
public final void init(int opmode,
Key key,
AlgorithmParameters params) throws InvalidKeyException, InvalidAlgorithmParameterException {
init(opmode, key, params, JceSecurity.RANDOM);
}
Initializes this cipher with a key and a set of algorithm
parameters.
The cipher is initialized for one of the following four operations:
encryption, decryption, key wrapping or key unwrapping, depending
on the value of opmode .
If this cipher requires any algorithm parameters and
params is null, the underlying cipher implementation is
supposed to generate the required parameters itself (using
provider-specific default or random values) if it is being
initialized for encryption or key wrapping, and raise an
InvalidAlgorithmParameterException if it is being
initialized for decryption or key unwrapping.
The generated parameters can be retrieved using
getParameters or
getIV (if the parameter is an IV).
If this cipher requires algorithm parameters that cannot be
derived from the input parameters, and there are no reasonable
provider-specific default values, initialization will
necessarily fail.
If this cipher (including its underlying feedback or padding scheme)
requires any random bytes (e.g., for parameter generation), it will get
them using the SecureRandom
implementation of the highest-priority
installed provider as the source of randomness.
(If none of the installed providers supply an implementation of
SecureRandom, a system-provided source of randomness will be used.)
Note that when a Cipher object is initialized, it loses all
previously-acquired state. In other words, initializing a Cipher is
equivalent to creating a new instance of that Cipher and initializing
it. |
public final void init(int opmode,
Certificate certificate,
SecureRandom random) throws InvalidKeyException {
initialized = false;
checkOpmode(opmode);
// Check key usage if the certificate is of
// type X.509.
if (certificate instanceof java.security.cert.X509Certificate) {
// Check whether the cert has a key usage extension
// marked as a critical extension.
X509Certificate cert = (X509Certificate)certificate;
Set critSet = cert.getCriticalExtensionOIDs();
if (critSet != null && !critSet.isEmpty()
&& critSet.contains(KEY_USAGE_EXTENSION_OID)) {
boolean[] keyUsageInfo = cert.getKeyUsage();
// keyUsageInfo[2] is for keyEncipherment;
// keyUsageInfo[3] is for dataEncipherment.
if ((keyUsageInfo != null) &&
(((opmode == Cipher.ENCRYPT_MODE) &&
(keyUsageInfo.length > 3) &&
(keyUsageInfo[3] == false)) ||
((opmode == Cipher.WRAP_MODE) &&
(keyUsageInfo.length > 2) &&
(keyUsageInfo[2] == false)))) {
throw new InvalidKeyException("Wrong key usage");
}
}
}
PublicKey publicKey =
(certificate==null? null:certificate.getPublicKey());
if (spi != null) {
checkCryptoPerm(spi, publicKey);
spi.engineInit(opmode, publicKey, random);
} else {
try {
chooseProvider(I_CERT, opmode, publicKey, null, null, random);
} catch (InvalidAlgorithmParameterException e) {
// should never occur
throw new InvalidKeyException(e);
}
}
initialized = true;
this.opmode = opmode;
}
Initializes this cipher with the public key from the given certificate
and
a source of randomness.
The cipher is initialized for one of the following four operations:
encryption, decryption, key wrapping
or key unwrapping, depending on
the value of opmode .
If the certificate is of type X.509 and has a key usage
extension field marked as critical, and the value of the key usage
extension field implies that the public key in
the certificate and its corresponding private key are not
supposed to be used for the operation represented by the value of
opmode ,
an InvalidKeyException
is thrown.
If this cipher requires any algorithm parameters that cannot be
derived from the public key in the given certificate ,
the underlying cipher
implementation is supposed to generate the required parameters itself
(using provider-specific default or random values) if it is being
initialized for encryption or key wrapping, and raise an
InvalidKeyException if it is being
initialized for decryption or key unwrapping.
The generated parameters can be retrieved using
getParameters or
getIV (if the parameter is an IV).
If this cipher requires algorithm parameters that cannot be
derived from the input parameters, and there are no reasonable
provider-specific default values, initialization will
necessarily fail.
If this cipher (including its underlying feedback or padding scheme)
requires any random bytes (e.g., for parameter generation), it will get
them from random .
Note that when a Cipher object is initialized, it loses all
previously-acquired state. In other words, initializing a Cipher is
equivalent to creating a new instance of that Cipher and initializing
it. |
public final void init(int opmode,
Key key,
AlgorithmParameterSpec params,
SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
initialized = false;
checkOpmode(opmode);
if (spi != null) {
checkCryptoPerm(spi, key, params);
spi.engineInit(opmode, key, params, random);
} else {
chooseProvider(I_PARAMSPEC, opmode, key, params, null, random);
}
initialized = true;
this.opmode = opmode;
}
Initializes this cipher with a key, a set of algorithm
parameters, and a source of randomness.
The cipher is initialized for one of the following four operations:
encryption, decryption, key wrapping or key unwrapping, depending
on the value of opmode .
If this cipher requires any algorithm parameters and
params is null, the underlying cipher implementation is
supposed to generate the required parameters itself (using
provider-specific default or random values) if it is being
initialized for encryption or key wrapping, and raise an
InvalidAlgorithmParameterException if it is being
initialized for decryption or key unwrapping.
The generated parameters can be retrieved using
getParameters or
getIV (if the parameter is an IV).
If this cipher requires algorithm parameters that cannot be
derived from the input parameters, and there are no reasonable
provider-specific default values, initialization will
necessarily fail.
If this cipher (including its underlying feedback or padding scheme)
requires any random bytes (e.g., for parameter generation), it will get
them from random .
Note that when a Cipher object is initialized, it loses all
previously-acquired state. In other words, initializing a Cipher is
equivalent to creating a new instance of that Cipher and initializing
it. |
public final void init(int opmode,
Key key,
AlgorithmParameters params,
SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
initialized = false;
checkOpmode(opmode);
if (spi != null) {
checkCryptoPerm(spi, key, params);
spi.engineInit(opmode, key, params, random);
} else {
chooseProvider(I_PARAMS, opmode, key, null, params, random);
}
initialized = true;
this.opmode = opmode;
}
Initializes this cipher with a key, a set of algorithm
parameters, and a source of randomness.
The cipher is initialized for one of the following four operations:
encryption, decryption, key wrapping or key unwrapping, depending
on the value of opmode .
If this cipher requires any algorithm parameters and
params is null, the underlying cipher implementation is
supposed to generate the required parameters itself (using
provider-specific default or random values) if it is being
initialized for encryption or key wrapping, and raise an
InvalidAlgorithmParameterException if it is being
initialized for decryption or key unwrapping.
The generated parameters can be retrieved using
getParameters or
getIV (if the parameter is an IV).
If this cipher requires algorithm parameters that cannot be
derived from the input parameters, and there are no reasonable
provider-specific default values, initialization will
necessarily fail.
If this cipher (including its underlying feedback or padding scheme)
requires any random bytes (e.g., for parameter generation), it will get
them from random .
Note that when a Cipher object is initialized, it loses all
previously-acquired state. In other words, initializing a Cipher is
equivalent to creating a new instance of that Cipher and initializing
it. |
public final Key unwrap(byte[] wrappedKey,
String wrappedKeyAlgorithm,
int wrappedKeyType) throws InvalidKeyException, NoSuchAlgorithmException {
if (!(this instanceof NullCipher)) {
if (!initialized) {
throw new IllegalStateException("Cipher not initialized");
}
if (opmode != Cipher.UNWRAP_MODE) {
throw new IllegalStateException("Cipher not initialized " +
"for unwrapping keys");
}
}
if ((wrappedKeyType != SECRET_KEY) &&
(wrappedKeyType != PRIVATE_KEY) &&
(wrappedKeyType != PUBLIC_KEY)) {
throw new InvalidParameterException("Invalid key type");
}
chooseFirstProvider();
return spi.engineUnwrap(wrappedKey,
wrappedKeyAlgorithm,
wrappedKeyType);
}
Unwrap a previously wrapped key. |
public final byte[] update(byte[] input) {
checkCipherState();
// Input sanity check
if (input == null) {
throw new IllegalArgumentException("Null input buffer");
}
chooseFirstProvider();
if (input.length == 0) {
return null;
}
return spi.engineUpdate(input, 0, input.length);
}
Continues a multiple-part encryption or decryption operation
(depending on how this cipher was initialized), processing another data
part.
The bytes in the input buffer are processed, and the
result is stored in a new buffer.
If input has a length of zero, this method returns
null . |
public final int update(ByteBuffer input,
ByteBuffer output) throws ShortBufferException {
checkCipherState();
if ((input == null) || (output == null)) {
throw new IllegalArgumentException("Buffers must not be null");
}
if (input == output) {
throw new IllegalArgumentException("Input and output buffers must "
+ "not be the same object, consider using buffer.duplicate()");
}
if (output.isReadOnly()) {
throw new ReadOnlyBufferException();
}
chooseFirstProvider();
return spi.engineUpdate(input, output);
}
Continues a multiple-part encryption or decryption operation
(depending on how this cipher was initialized), processing another data
part.
All input.remaining() bytes starting at
input.position() are processed. The result is stored
in the output buffer.
Upon return, the input buffer's position will be equal
to its limit; its limit will not have changed. The output buffer's
position will have advanced by n, where n is the value returned
by this method; the output buffer's limit will not have changed.
If output.remaining() bytes are insufficient to
hold the result, a ShortBufferException is thrown.
In this case, repeat this call with a larger output buffer. Use
getOutputSize to determine how big
the output buffer should be.
Note: this method should be copy-safe, which means the
input and output buffers can reference
the same block of memory and no unprocessed input data is overwritten
when the result is copied into the output buffer. |
public final byte[] update(byte[] input,
int inputOffset,
int inputLen) {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
if (inputLen == 0) {
return null;
}
return spi.engineUpdate(input, inputOffset, inputLen);
}
Continues a multiple-part encryption or decryption operation
(depending on how this cipher was initialized), processing another data
part.
The first inputLen bytes in the input
buffer, starting at inputOffset inclusive, are processed,
and the result is stored in a new buffer.
If inputLen is zero, this method returns
null . |
public final int update(byte[] input,
int inputOffset,
int inputLen,
byte[] output) throws ShortBufferException {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
if (inputLen == 0) {
return 0;
}
return spi.engineUpdate(input, inputOffset, inputLen,
output, 0);
}
Continues a multiple-part encryption or decryption operation
(depending on how this cipher was initialized), processing another data
part.
The first inputLen bytes in the input
buffer, starting at inputOffset inclusive, are processed,
and the result is stored in the output buffer.
If the output buffer is too small to hold the result,
a ShortBufferException is thrown. In this case, repeat this
call with a larger output buffer. Use
getOutputSize to determine how big
the output buffer should be.
If inputLen is zero, this method returns
a length of zero.
Note: this method should be copy-safe, which means the
input and output buffers can reference
the same byte array and no unprocessed input data is overwritten
when the result is copied into the output buffer. |
public final int update(byte[] input,
int inputOffset,
int inputLen,
byte[] output,
int outputOffset) throws ShortBufferException {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0
|| outputOffset < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
if (inputLen == 0) {
return 0;
}
return spi.engineUpdate(input, inputOffset, inputLen,
output, outputOffset);
}
Continues a multiple-part encryption or decryption operation
(depending on how this cipher was initialized), processing another data
part.
The first inputLen bytes in the input
buffer, starting at inputOffset inclusive, are processed,
and the result is stored in the output buffer, starting at
outputOffset inclusive.
If the output buffer is too small to hold the result,
a ShortBufferException is thrown. In this case, repeat this
call with a larger output buffer. Use
getOutputSize to determine how big
the output buffer should be.
If inputLen is zero, this method returns
a length of zero.
Note: this method should be copy-safe, which means the
input and output buffers can reference
the same byte array and no unprocessed input data is overwritten
when the result is copied into the output buffer. |
public final void updateAAD(byte[] src) {
if (src == null) {
throw new IllegalArgumentException("src buffer is null");
}
updateAAD(src, 0, src.length);
}
Continues a multi-part update of the Additional Authentication
Data (AAD).
Calls to this method provide AAD to the cipher when operating in
modes such as AEAD (GCM/CCM). If this cipher is operating in
either GCM or CCM mode, all AAD must be supplied before beginning
operations on the ciphertext (via the {@code update} and {@code
doFinal} methods). |
public final void updateAAD(ByteBuffer src) {
checkCipherState();
// Input sanity check
if (src == null) {
throw new IllegalArgumentException("src ByteBuffer is null");
}
chooseFirstProvider();
if (src.remaining() == 0) {
return;
}
spi.engineUpdateAAD(src);
}
Continues a multi-part update of the Additional Authentication
Data (AAD).
Calls to this method provide AAD to the cipher when operating in
modes such as AEAD (GCM/CCM). If this cipher is operating in
either GCM or CCM mode, all AAD must be supplied before beginning
operations on the ciphertext (via the {@code update} and {@code
doFinal} methods).
All {@code src.remaining()} bytes starting at
{@code src.position()} are processed.
Upon return, the input buffer's position will be equal
to its limit; its limit will not have changed. |
public final void updateAAD(byte[] src,
int offset,
int len) {
checkCipherState();
// Input sanity check
if ((src == null) || (offset < 0) || (len < 0)
|| ((len + offset) > src.length)) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
if (len == 0) {
return;
}
spi.engineUpdateAAD(src, offset, len);
}
Continues a multi-part update of the Additional Authentication
Data (AAD), using a subset of the provided buffer.
Calls to this method provide AAD to the cipher when operating in
modes such as AEAD (GCM/CCM). If this cipher is operating in
either GCM or CCM mode, all AAD must be supplied before beginning
operations on the ciphertext (via the {@code update} and {@code
doFinal} methods). |
public final byte[] wrap(Key key) throws IllegalBlockSizeException, InvalidKeyException {
if (!(this instanceof NullCipher)) {
if (!initialized) {
throw new IllegalStateException("Cipher not initialized");
}
if (opmode != Cipher.WRAP_MODE) {
throw new IllegalStateException("Cipher not initialized " +
"for wrapping keys");
}
}
chooseFirstProvider();
return spi.engineWrap(key);
}
|