org.bouncycastle.cms.PasswordRecipientInfoGenerator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of bcmail-jdk15 Show documentation
Show all versions of bcmail-jdk15 Show documentation
The Bouncy Castle Java CMS and S/MIME APIs for handling the CMS and S/MIME protocols. This jar contains CMS and S/MIME APIs for JDK 1.5. The APIs can be used in conjunction with a JCE/JCA provider such as the one provided with the Bouncy Castle Cryptography APIs. If the S/MIME API is used, the JavaMail API and the Java activation framework will also be needed.
package org.bouncycastle.cms;
import java.security.GeneralSecurityException;
import java.security.Provider;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.cms.PasswordRecipientInfo;
import org.bouncycastle.asn1.cms.RecipientInfo;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
class PasswordRecipientInfoGenerator implements RecipientInfoGenerator
{
private AlgorithmIdentifier derivationAlg;
private SecretKey wrapKey;
PasswordRecipientInfoGenerator()
{
}
void setDerivationAlg(AlgorithmIdentifier derivationAlg)
{
this.derivationAlg = derivationAlg;
}
void setWrapKey(SecretKey wrapKey)
{
this.wrapKey = wrapKey;
}
public RecipientInfo generate(SecretKey key, SecureRandom random,
Provider prov) throws GeneralSecurityException
{
// TODO Consider passing in the wrapAlgorithmOID instead
CMSEnvelopedHelper helper = CMSEnvelopedHelper.INSTANCE;
String wrapAlgName = helper.getRFC3211WrapperName(wrapKey.getAlgorithm());
Cipher keyCipher = helper.createAsymmetricCipher(wrapAlgName, prov);
keyCipher.init(Cipher.WRAP_MODE, wrapKey, random);
ASN1OctetString encKey = new DEROctetString(keyCipher.wrap(key));
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(wrapKey.getAlgorithm()));
v.add(new DEROctetString(keyCipher.getIV()));
AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(
PKCSObjectIdentifiers.id_alg_PWRI_KEK, new DERSequence(v));
return new RecipientInfo(new PasswordRecipientInfo(derivationAlg,
keyEncAlg, encKey));
}
}