Example usage for org.bouncycastle.asn1 DERNull DERNull

List of usage examples for org.bouncycastle.asn1 DERNull DERNull

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 DERNull DERNull.

Prototype

public DERNull() 

Source Link

Usage

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

private DERSequence siAddDigestAlgorithm(String hashId) {
    // Add the digestEncAlgorithm
    ASN1EncodableVector digestVetor = new ASN1EncodableVector();
    digestVetor.add(new DERObjectIdentifier(hashId)); // 6 OID
    digestVetor.add(new DERNull()); // 6 NULL
    return new DERSequence(digestVetor); // 5 SEQ
}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

private void buildDigestAlg(final ASN1EncodableVector body, String hashId) {
    // ---------- algoritmos de digest
    final ASN1EncodableVector algos = new ASN1EncodableVector();
    algos.add(new DERObjectIdentifier(hashId)); // 4 OID
    algos.add(new DERNull()); // 4 NULL
    final ASN1EncodableVector algoSet = new ASN1EncodableVector();
    algoSet.add(new DERSequence(algos));
    final DERSet digestAlgorithms = new DERSet(algoSet); // 2
    // SET//  w w w .j a  va 2  s .  com
    body.add(digestAlgorithms);
}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

private void buildDigestAlg(final ASN1EncodableVector body, List<String> listHashId) {
    // ---------- algoritmos de digest
    final ASN1EncodableVector algos = new ASN1EncodableVector();
    for (String next : listHashId) {
        algos.add(new DERObjectIdentifier(next)); // 4 OID
        algos.add(new DERNull()); // 4 NULL
    }//from  w  ww . ja va 2  s  .  c om

    final ASN1EncodableVector algoSet = new ASN1EncodableVector();

    algoSet.add(new DERSequence(algos));
    final DERSet digestAlgorithms = new DERSet(algoSet); // 2
    // SET
    body.add(digestAlgorithms);
}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

public static AlgorithmIdentifier createAlgorithm(int hashId) throws Exception {
    return new AlgorithmIdentifier(new ASN1ObjectIdentifier(DerEncoder.getHashAlg(hashId)), new DERNull());
}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.attribute.BCSignaturePolicyIdentifier.java

License:Open Source License

/**
 * TODO: Implementar a converso do tipo SigPolicyQualifierInfoUserNotice
 * para BC./*from  w ww .  j a v  a  2  s . c  o m*/
 *
 * @return
 */
@Override
public ASN1Set getValue() {
    if (super.getAttribute() == null) {
        org.bouncycastle.asn1.esf.SignaturePolicyIdentifier signaturePolicyIdentifier = new org.bouncycastle.asn1.esf.SignaturePolicyIdentifier();
        return new DERSet(signaturePolicyIdentifier);
    }
    SignaturePolicyId signaturePolicyId = ((SignaturePolicyIdentifier) super.getAttribute())
            .getSignaturePolicyId();
    if (signaturePolicyId != null) {
        DERObjectIdentifier objectIdentifier = new DERObjectIdentifier(signaturePolicyId.getSigPolicyId());
        OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(
                new AlgorithmIdentifier(signaturePolicyId.getHashAlgorithm()),
                new DEROctetString(signaturePolicyId.getHash()));
        SigPolicyQualifiers sigPolicyQualifiers = null;
        if (signaturePolicyId.getSigPolicyQualifiers() != null
                && signaturePolicyId.getSigPolicyQualifiers().size() > 0) {
            List<SigPolicyQualifierInfo> sigPolicyQualifierInfos = new ArrayList<SigPolicyQualifierInfo>();
            for (br.gov.frameworkdemoiselle.certificate.signer.pkcs7.attribute.SigPolicyQualifierInfo sigPolicyQualifierInfo : signaturePolicyId
                    .getSigPolicyQualifiers()) {
                if (sigPolicyQualifierInfo instanceof SigPolicyQualifierInfoURL) {
                    SigPolicyQualifierInfoURL sigPolicyQualifierInfoURL = (SigPolicyQualifierInfoURL) sigPolicyQualifierInfo;
                    DERObjectIdentifier oi = new DERObjectIdentifier(sigPolicyQualifierInfoURL.getOID());
                    DERIA5String url = new DERIA5String(sigPolicyQualifierInfoURL.getValue());
                    SigPolicyQualifierInfo bcSigPolicyQualifierInfo = new SigPolicyQualifierInfo(oi, url);
                    sigPolicyQualifierInfos.add(bcSigPolicyQualifierInfo);
                }
            }
            sigPolicyQualifiers = new SigPolicyQualifiers(
                    sigPolicyQualifierInfos.toArray(new SigPolicyQualifierInfo[] {}));
        }
        org.bouncycastle.asn1.esf.SignaturePolicyId bcSignaturePolicyId = new org.bouncycastle.asn1.esf.SignaturePolicyId(
                objectIdentifier, otherHashAlgAndValue, sigPolicyQualifiers);
        org.bouncycastle.asn1.esf.SignaturePolicyIdentifier signaturePolicyIdentifier = new org.bouncycastle.asn1.esf.SignaturePolicyIdentifier(
                bcSignaturePolicyId);
        return new DERSet(signaturePolicyIdentifier);
    }
    return new DERSet(new DERNull());
}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.attribute.BCSigningCertificate.java

License:Open Source License

@Override
public ASN1Set getValue() {
    SigningCertificate attribute = (SigningCertificate) super.getAttribute();
    X509Certificate cert = attribute.getValue();
    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(DigestAlgorithmEnum.SHA_1);
    byte[] certHash = null;
    try {//from   w w  w.  j  ava 2 s.  c o  m
        certHash = digest.digest(cert.getEncoded());
    } catch (CertificateEncodingException ex) {
        ex.printStackTrace();
    }
    X509Name dirName = new X509Name(cert.getSubjectDN().getName());
    GeneralName name = new GeneralName(dirName);
    GeneralNames issuer = new GeneralNames(name);
    DERInteger serialNumber = new DERInteger(cert.getSerialNumber());
    IssuerSerial issuerSerial = new IssuerSerial(issuer, serialNumber);
    ESSCertID essCertId = new ESSCertID(certHash, issuerSerial);
    return new DERSet(new DERSequence(
            new ASN1Encodable[] { new DERSequence(essCertId), new DERSequence(new DERNull()) }));
}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.attribute.BCSigningCertificateV2.java

License:Open Source License

@Override
public ASN1Set getValue() {
    SigningCertificateV2 attribute = (SigningCertificateV2) super.getAttribute();
    X509Certificate cert = attribute.getValue();
    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
    byte[] certHash = null;
    try {/* w w w  .j  a va 2  s  .c  o m*/
        certHash = digest.digest(cert.getEncoded());
    } catch (CertificateEncodingException ex) {
        ex.printStackTrace();

    }
    X509Name dirName = new X509Name(cert.getSubjectDN().getName());
    GeneralName name = new GeneralName(dirName);
    GeneralNames issuer = new GeneralNames(name);
    DERInteger serial = new DERInteger(cert.getSerialNumber());
    IssuerSerial issuerSerial = new IssuerSerial(issuer, serial);
    String algorithmHashOID = SignerAlgorithmEnum.getSignerAlgorithmEnum(attribute.getAlgorithmHash())
            .getOIDAlgorithmHash();
    AlgorithmIdentifier algorithmId = new AlgorithmIdentifier(algorithmHashOID);
    ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(algorithmId, certHash, issuerSerial);
    return new DERSet(new DERSequence(
            new ASN1Encodable[] { new DERSequence(essCertIDv2), new DERSequence(new DERNull()) }));
}

From source file:ch.bfh.unicert.certimport.CertificateIssuer.java

License:GNU General Public License

public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity,
        String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL,
        String section) throws CertificateCreationException {

    X509Certificate caCert;/* w ww  .j  ava  2  s.c  om*/
    RSAPrivateCrtKey privKey;
    try {
        caCert = this.readIssuerCertificate(this.issuerId);
        privKey = this.readPrivateKey(this.issuerId, this.privKeyPass);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) {
        logger.log(Level.SEVERE, null, ex);
        throw new CertificateCreationException("230 Could not create client certificate. Key error");
    }

    RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey);

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(getExpiryDate(validity).getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException
            | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(),
            id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(),
            id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles,
            id.getIdentityProvider(), extensionMap);

    //post message on UniBoard if corresponding JNDI parameter is defined
    postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(),
            privKey);

    return cert;

}

From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java

License:GNU General Public License

/**
 * Actually creates the requestor certificate.
 *
 * @param id requestor identity data/*  www.j av a  2  s.  co m*/
 * @param caCert certificate of the certification authority
 * @param cipherParams issuer private key parameters used for signing
 * @param pk public key of the requestor to certify
 * @param expiry the expiry date
 * @param applicationIdentifier the application identifier for which te certificate is issued
 * @param role role for which the certificate is issued
 * @return the certificate object containing the X509 certificate
 * @throws CertificateCreationException if an error occurs
 */
private Certificate createClientCertificate(IdentityData id, X509Certificate caCert,
        CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier,
        String[] roles) throws CertificateCreationException {

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(expiry.getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException
            | NoSuchProviderException | InvalidCipherTextException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(),
            id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(),
            id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap);

}

From source file:com.aaasec.sigserv.csspsupport.pdfbox.DigestAlgorithm.java

License:EUPL

/**
 * Gets the ASN.1 algorithm identifier structure corresponding to this digest algorithm
 * /*from   www .j a va 2  s . c  om*/
 * @return the AlgorithmIdentifier
 */
public AlgorithmIdentifier getAlgorithmIdentifier() {
    /*
     * The recommendation (cf. RFC 3380 section 2.1) is to omit the parameter for SHA-1, but some implementations
     * still expect a NULL there. Therefore we always include a NULL parameter even with SHA-1, despite the
     * recommendation, because the RFC states that implementations SHOULD support it as well anyway
     */
    return new AlgorithmIdentifier(new DERObjectIdentifier(this.getOid()), new DERNull());
}