Example usage for org.bouncycastle.asn1.x509 Time Time

List of usage examples for org.bouncycastle.asn1.x509 Time Time

Introduction

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

Prototype

public Time(Date time) 

Source Link

Document

Creates a time object from a given date - if the date is between 1950 and 2049 a UTCTime object is generated, otherwise a GeneralizedTime is used.

Usage

From source file:AAModulePackage.ACHelper.java

/**
 * This method takes in an AC and wraps it up in the wrapper class.
 * @param ac - X509AttributeCertificateHold that we want to wrap.
 * @return wrapped up AC.//  ww  w . j a  va 2 s  .  c o  m
 */
public static AttributeCertificateWrapper extractAttributes(X509AttributeCertificateHolder ac) {
    AttributeCertificateWrapper wrapper = new AttributeCertificateWrapper(ac);

    for (Attribute a : ac.getAttributes(NewAttributeIdentifiers.role)) {
        ASN1Set set = a.getAttrValues();
        String s = DERGeneralString.getInstance(set.getObjectAt(0)).getString();
        wrapper.setRole(s);
    }

    for (Attribute a : ac.getAttributes(NewAttributeIdentifiers.record_id)) {
        ASN1Set set = a.getAttrValues();
        String s = DERGeneralString.getInstance(set.getObjectAt(0)).getString();
        wrapper.setRecordId(s);
    }

    for (Attribute a : ac.getAttributes(NewAttributeIdentifiers.time_stamp)) {
        ASN1Set set = a.getAttrValues();
        Time t = new Time(set.getObjectAt(0).toASN1Primitive());
        wrapper.setTimeStamp(t);
    }

    for (Attribute a : ac.getAttributes(NewAttributeIdentifiers.record_type)) {
        ASN1Set set = a.getAttrValues();
        String[] arr = new String[set.size()];
        for (int i = 0; i < set.size(); ++i) {
            arr[i] = DERGeneralString.getInstance(set.getObjectAt(i)).getString();
        }
        wrapper.setRecordTypes(arr);
    }

    for (Attribute a : ac.getAttributes(NewAttributeIdentifiers.record_subject)) {
        ASN1Set set = a.getAttrValues();
        String s = DERGeneralString.getInstance(set.getObjectAt(0)).getString();
        wrapper.setRecord_subject(s);
    }

    for (Attribute a : ac.getAttributes(NewAttributeIdentifiers.actions_taken)) {
        ASN1Set set = a.getAttrValues();
        String[] arr = new String[set.size()];
        for (int i = 0; i < set.size(); ++i) {
            arr[i] = DERGeneralString.getInstance(set.getObjectAt(i)).getString();
        }
        wrapper.setActions_taken(arr);
    }
    return wrapper;
}

From source file:cc.arduino.plugins.unowifi.certs.WiFi101Certificate.java

License:Open Source License

private static byte[] encodeTimestamp(Date notBefore) throws IOException {
    ByteArrayOutputStream encoded = new ByteArrayOutputStream();
    ASN1OutputStream asn1 = new ASN1OutputStream(encoded);
    asn1.writeObject(new Time(notBefore));
    return Arrays.copyOfRange(encoded.toByteArray(), 2, 22);
}

From source file:cc.arduino.plugins.wifi101.certs.WiFi101Certificate.java

License:Open Source License

private static byte[] encodeTimestampV0(Date notBefore) throws IOException {
    ByteArrayOutputStream encoded = new ByteArrayOutputStream();
    ASN1OutputStream asn1 = new ASN1OutputStream(encoded);
    asn1.writeObject(new Time(notBefore));
    return Arrays.copyOfRange(encoded.toByteArray(), 2, 22);
}

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;//from   w w  w . ja  v a 2 s .  com
    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/*from ww w . ja va  2 s .  c o  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.vmware.identity.rest.core.test.util.CertificateGenerator.java

License:Open Source License

/**
 * Generate a self-signed X.509 certificate
 *
 * @param pair the key pair to use when signing the certificate
 * @param algorithm the signing algorithm to use
 * @param dn the X.509 distinguished name for the certificate
 * @return a self-signed X.509 certificate
 * @throws NoSuchAlgorithmException/*from   w  ww  .  j  av  a  2s .c om*/
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws IOException
 * @throws CertificateException
 */
public static X509Certificate generateSelfSignedCertificate(KeyPair pair, AlgorithmName algorithm, String dn)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException,
        IOException, CertificateException {
    if (Security.getProvider("BC") == null) {
        Security.addProvider(new BouncyCastleProvider());
    }

    AtomicLong serialNumber = new AtomicLong(System.currentTimeMillis());
    X500Name owner = new X500Name(dn);

    V1TBSCertificateGenerator generator = new V1TBSCertificateGenerator();
    long time = System.currentTimeMillis();

    generator.setSerialNumber(new ASN1Integer(serialNumber.getAndIncrement()));
    generator.setIssuer(owner);
    generator.setSubject(owner);
    generator.setStartDate(new Time(new Date(time - 5000)));
    generator.setEndDate(new Time(new Date(time + 30 * 60 * 1000)));
    generator.setSignature(ALGORITHM_IDS.get(algorithm));
    generator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()));

    Signature sig = Signature.getInstance(algorithm.toString(), "BC");

    sig.initSign(pair.getPrivate());

    sig.update(generator.generateTBSCertificate().getEncoded(ASN1Encoding.DER));

    TBSCertificate tbsCert = generator.generateTBSCertificate();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(ALGORITHM_IDS.get(algorithm));
    v.add(new DERBitString(sig.sign()));

    return (X509Certificate) CertificateFactory.getInstance("X.509", "BC")
            .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
}

From source file:eu.emi.security.authn.x509.helpers.proxy.X509v3CertificateBuilder.java

License:Open Source License

/**
 * Create a builder for a version 3 certificate.
 * // www.  ja va 2  s. co m
 * @param issuer the certificate issuer
 * @param serial the certificate serial number
 * @param notBefore the date before which the certificate is not valid
 * @param notAfter the date after which the certificate is not valid
 * @param subject the certificate subject
 * @param publicKeyInfo the info structure for the public key to be associated
 * with this certificate.
 */
public X509v3CertificateBuilder(X500Name issuer, BigInteger serial, Date notBefore, Date notAfter,
        X500Name subject, SubjectPublicKeyInfo publicKeyInfo) {
    tbsGen = new V3TBSCertificateGenerator();
    tbsGen.setSubject(subject);
    tbsGen.setSerialNumber(new ASN1Integer(serial));
    tbsGen.setIssuer(issuer);
    tbsGen.setStartDate(new Time(notBefore));
    tbsGen.setEndDate(new Time(notAfter));
    tbsGen.setSubject(subject);
    tbsGen.setSubjectPublicKeyInfo(publicKeyInfo);
    extGenerator = new ExtensionsGenerator();
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESLevelBaselineB.java

License:Open Source License

private void addSigningTimeAttribute(final SignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) {

    if (!padesUsage) {
        /*/*www.  ja  v a2s  . com*/
         * In PAdES, we don't include the signing time : ETSI TS 102 778-3 V1.2.1 (2010-07): 4.5.3 signing-time
           * Attribute
           */
        final Date signingDate = parameters.bLevel().getSigningDate();
        if (signingDate != null) {

            final DERSet attrValues = new DERSet(new Time(signingDate));
            final Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_signingTime, attrValues);
            signedAttributes.add(attribute);
        }
    }
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileBES.java

License:Open Source License

private Attribute makeSigningTimeAttribute(SignatureParameters parameters) {
    return new Attribute(PKCSObjectIdentifiers.pkcs_9_at_signingTime,
            new DERSet(new Time(parameters.getSigningDate())));
}

From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBaselineB.java

License:Open Source License

private void addSigningTimeAttribute(final CAdESSignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) {

    if (!padesUsage) {
        /*/*  w w  w  .  j a  v a  2  s  .co  m*/
         * In PAdES, we don't include the signing time : ETSI TS 102 778-3 V1.2.1 (2010-07): 4.5.3 signing-time
         * Attribute
         */
        final Date signingDate = parameters.bLevel().getSigningDate();
        if (signingDate != null) {

            final DERSet attrValues = new DERSet(new Time(signingDate));
            final Attribute attribute = new Attribute(pkcs_9_at_signingTime, attrValues);
            signedAttributes.add(attribute);
        }
    }
}