Example usage for org.bouncycastle.operator ContentSigner getAlgorithmIdentifier

List of usage examples for org.bouncycastle.operator ContentSigner getAlgorithmIdentifier

Introduction

In this page you can find the example usage for org.bouncycastle.operator ContentSigner getAlgorithmIdentifier.

Prototype

AlgorithmIdentifier getAlgorithmIdentifier();

Source Link

Document

Return the algorithm identifier describing the signature algorithm and parameters this signer generates.

Usage

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Generates a PKCS10CertificationRequest
 * //from ww  w  .j av  a 2  s .c om
 * Code Example:
 * -------------
 * An example of putting AltName and a password challenge in an 'attributes' set (taken from RequestMessageTest.test01Pkcs10RequestMessage() ):
 *       
 *      {@code
 *      // Create a P10 with extensions, in this case altNames with a DNS name
 *      ASN1EncodableVector altnameattr = new ASN1EncodableVector();
 *      altnameattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
 *      // AltNames
 *      GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foo1.bar.com");
 *      ExtensionsGenerator extgen = new ExtensionsGenerator();
 *      extgen.addExtension(Extension.subjectAlternativeName, false, san );
 *      Extensions exts = extgen.generate();
 *      altnameattr.add(new DERSet(exts));
 *    
 *      // Add a challenge password as well
 *      ASN1EncodableVector pwdattr = new ASN1EncodableVector();
 *      pwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); 
 *      ASN1EncodableVector pwdvalues = new ASN1EncodableVector();
 *      pwdvalues.add(new DERUTF8String("foo123"));
 *      pwdattr.add(new DERSet(pwdvalues));
 *    
 *      // Complete the Attribute section of the request, the set (Attributes)
 *      // contains one sequence (Attribute)
 *      ASN1EncodableVector v = new ASN1EncodableVector();
 *      v.add(new DERSequence(altnameattr));
 *      v.add(new DERSequence(pwdattr));
 *      DERSet attributes = new DERSet(v);
 *      }
 * 
 * @param signatureAlgorithm
 * @param subject   The request's subjectDN
 * @param publickey the public key for the certificate requesting signing
 * @param attributes    A set of attributes, for example, extensions, challenge password, etc.
 * @param privateKey the private key used to generate the certificate
 * @param provider
 * @return a PKCS10CertificateRequest based on the input parameters.
 * 
 * @throws OperatorCreationException if an error occurred while creating the signing key
 */
public static PKCS10CertificationRequest genPKCS10CertificationRequest(String signatureAlgorithm,
        X500Name subject, PublicKey publickey, ASN1Set attributes, PrivateKey privateKey, String provider)
        throws OperatorCreationException {

    ContentSigner signer;
    CertificationRequestInfo reqInfo;
    try {
        ASN1Sequence seq = (ASN1Sequence) ASN1Primitive.fromByteArray(publickey.getEncoded());
        SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(seq);
        reqInfo = new CertificationRequestInfo(subject, pkinfo, attributes);

        if (provider == null) {
            provider = BouncyCastleProvider.PROVIDER_NAME;
        }
        signer = new BufferingContentSigner(
                new JcaContentSignerBuilder(signatureAlgorithm).setProvider(provider).build(privateKey), 20480);
        signer.getOutputStream().write(reqInfo.getEncoded(ASN1Encoding.DER));
        signer.getOutputStream().flush();
    } catch (IOException e) {
        throw new IllegalStateException("Unexpected IOException was caught.", e);
    }
    byte[] sig = signer.getSignature();
    DERBitString sigBits = new DERBitString(sig);

    CertificationRequest req = new CertificationRequest(reqInfo, signer.getAlgorithmIdentifier(), sigBits);
    return new PKCS10CertificationRequest(req);
}

From source file:org.jruby.ext.openssl.OCSPBasicResponse.java

License:Common Public License

@JRubyMethod(name = "sign", rest = true)
public IRubyObject sign(final ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.getRuntime();

    int flag = 0;
    IRubyObject additionalCerts = context.nil;
    IRubyObject flags = context.nil;//from  w w  w .j  a v a 2 s. com
    IRubyObject digest = context.nil;
    Digest digestInstance = new Digest(runtime, _Digest(runtime));
    List<X509CertificateHolder> addlCerts = new ArrayList<X509CertificateHolder>();

    switch (Arity.checkArgumentCount(runtime, args, 2, 5)) {
    case 3:
        additionalCerts = args[2];
        break;
    case 4:
        additionalCerts = args[2];
        flags = args[3];
        break;
    case 5:
        additionalCerts = args[2];
        flags = args[3];
        digest = args[4];
        break;
    default:
        break;
    }

    if (digest.isNil())
        digest = digestInstance.initialize(context,
                new IRubyObject[] { RubyString.newString(runtime, "SHA1") });
    if (!flags.isNil())
        flag = RubyFixnum.fix2int(flags);
    if (additionalCerts.isNil())
        flag |= RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCERTS));

    X509Cert signer = (X509Cert) args[0];
    PKey signerKey = (PKey) args[1];

    String keyAlg = signerKey.getAlgorithm();
    String digAlg = ((Digest) digest).getShortAlgorithm();

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(digAlg + "with" + keyAlg);
    signerBuilder.setProvider("BC");
    ContentSigner contentSigner = null;
    try {
        contentSigner = signerBuilder.build(signerKey.getPrivateKey());
    } catch (OperatorCreationException e) {
        throw newOCSPError(runtime, e);
    }

    BasicOCSPRespBuilder respBuilder = null;
    try {
        if ((flag & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_RESPID_KEY))) != 0) {
            JcaDigestCalculatorProviderBuilder dcpb = new JcaDigestCalculatorProviderBuilder();
            dcpb.setProvider("BC");
            DigestCalculatorProvider dcp = dcpb.build();
            DigestCalculator calculator = dcp.get(contentSigner.getAlgorithmIdentifier());
            respBuilder = new BasicOCSPRespBuilder(
                    SubjectPublicKeyInfo.getInstance(signerKey.getPublicKey().getEncoded()), calculator);
        } else {
            respBuilder = new BasicOCSPRespBuilder(new RespID(signer.getSubject().getX500Name()));
        }
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }

    X509CertificateHolder[] chain = null;
    try {
        if ((flag & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCERTS))) == 0) {
            addlCerts.add(new X509CertificateHolder(signer.getAuxCert().getEncoded()));
            if (!additionalCerts.isNil()) {
                Iterator<java.security.cert.Certificate> rubyAddlCerts = ((RubyArray) additionalCerts)
                        .iterator();
                while (rubyAddlCerts.hasNext()) {
                    java.security.cert.Certificate cert = rubyAddlCerts.next();
                    addlCerts.add(new X509CertificateHolder(cert.getEncoded()));
                }
            }

            chain = addlCerts.toArray(new X509CertificateHolder[addlCerts.size()]);
        }
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }

    Date producedAt = null;
    if ((flag & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOTIME))) == 0) {
        producedAt = new Date();
    }

    for (OCSPSingleResponse resp : singleResponses) {
        SingleResp singleResp = new SingleResp(resp.getBCSingleResp());
        respBuilder.addResponse(singleResp.getCertID(), singleResp.getCertStatus(), singleResp.getThisUpdate(),
                singleResp.getNextUpdate(), resp.getBCSingleResp().getSingleExtensions());
    }

    try {
        Extension[] respExtAry = new Extension[extensions.size()];
        Extensions respExtensions = new Extensions(extensions.toArray(respExtAry));
        BasicOCSPResp bcBasicOCSPResp = respBuilder.setResponseExtensions(respExtensions).build(contentSigner,
                chain, producedAt);
        asn1BCBasicOCSPResp = BasicOCSPResponse.getInstance(bcBasicOCSPResp.getEncoded());
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }
    return this;
}