diff options
Diffstat (limited to 'pkix/src/main/java/org/spongycastle/operator/bc/BcAsymmetricKeyWrapper.java')
-rw-r--r-- | pkix/src/main/java/org/spongycastle/operator/bc/BcAsymmetricKeyWrapper.java | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/pkix/src/main/java/org/spongycastle/operator/bc/BcAsymmetricKeyWrapper.java b/pkix/src/main/java/org/spongycastle/operator/bc/BcAsymmetricKeyWrapper.java new file mode 100644 index 00000000..8b5bb3e8 --- /dev/null +++ b/pkix/src/main/java/org/spongycastle/operator/bc/BcAsymmetricKeyWrapper.java @@ -0,0 +1,60 @@ +package org.spongycastle.operator.bc; + +import java.security.SecureRandom; + +import org.spongycastle.asn1.ASN1ObjectIdentifier; +import org.spongycastle.asn1.x509.AlgorithmIdentifier; +import org.spongycastle.crypto.AsymmetricBlockCipher; +import org.spongycastle.crypto.CipherParameters; +import org.spongycastle.crypto.InvalidCipherTextException; +import org.spongycastle.crypto.params.AsymmetricKeyParameter; +import org.spongycastle.crypto.params.ParametersWithRandom; +import org.spongycastle.operator.AsymmetricKeyWrapper; +import org.spongycastle.operator.GenericKey; +import org.spongycastle.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, publicKey); + 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); +} |