All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.gatling.recorder.internal.bouncycastle.operator.bc.BcAsymmetricKeyWrapper Maven / Gradle / Ivy

package io.gatling.recorder.internal.bouncycastle.operator.bc;

import java.security.SecureRandom;

import io.gatling.recorder.internal.bouncycastle.asn1.ASN1ObjectIdentifier;
import io.gatling.recorder.internal.bouncycastle.asn1.x509.AlgorithmIdentifier;
import io.gatling.recorder.internal.bouncycastle.crypto.AsymmetricBlockCipher;
import io.gatling.recorder.internal.bouncycastle.crypto.CipherParameters;
import io.gatling.recorder.internal.bouncycastle.crypto.InvalidCipherTextException;
import io.gatling.recorder.internal.bouncycastle.crypto.params.AsymmetricKeyParameter;
import io.gatling.recorder.internal.bouncycastle.crypto.params.ParametersWithRandom;
import io.gatling.recorder.internal.bouncycastle.operator.AsymmetricKeyWrapper;
import io.gatling.recorder.internal.bouncycastle.operator.GenericKey;
import io.gatling.recorder.internal.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);
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy