org.bouncycastle.operator.bc.BcAsymmetricKeyWrapper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of bcpkix-jdk15to18 Show documentation
Show all versions of bcpkix-jdk15to18 Show documentation
The Bouncy Castle Java APIs for CMS, PKCS, EAC, TSP, CMP, CRMF, OCSP, and certificate generation. This jar contains APIs for JDK 1.5 to JDK 1.8. The APIs can be used in conjunction with a JCE/JCA provider such as the one provided with the Bouncy Castle Cryptography APIs.
package org.bouncycastle.operator.bc;
import java.security.SecureRandom;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.operator.AsymmetricKeyWrapper;
import org.bouncycastle.operator.GenericKey;
import org.bouncycastle.operator.OperatorException;
public abstract class BcAsymmetricKeyWrapper
extends AsymmetricKeyWrapper
{
private AsymmetricKeyParameter publicKey;
private SecureRandom random;
public BcAsymmetricKeyWrapper(AlgorithmIdentifier encAlgId, AsymmetricKeyParameter publicKey)
{
super(encAlgId);
this.publicKey = publicKey;
}
public BcAsymmetricKeyWrapper setSecureRandom(SecureRandom random)
{
this.random = random;
return this;
}
public byte[] generateWrappedKey(GenericKey encryptionKey)
throws OperatorException
{
AsymmetricBlockCipher keyEncryptionCipher = createAsymmetricWrapper(getAlgorithmIdentifier().getAlgorithm());
CipherParameters params = publicKey;
if (random != null)
{
params = new ParametersWithRandom(params, random);
}
try
{
byte[] keyEnc = OperatorUtils.getKeyBytes(encryptionKey);
keyEncryptionCipher.init(true, params);
return keyEncryptionCipher.processBlock(keyEnc, 0, keyEnc.length);
}
catch (InvalidCipherTextException e)
{
throw new OperatorException("unable to encrypt contents key", e);
}
}
protected abstract AsymmetricBlockCipher createAsymmetricWrapper(ASN1ObjectIdentifier algorithm);
}