Search in sources :

Example 6 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project robovm by robovm.

the class X509V3CertificateGenerator method generate.

/**
     * generate an X509 certificate, based on the current issuer and subject
     * using the default provider, and the passed in source of randomness
     * (if required).
     * <p>
     * <b>Note:</b> this differs from the deprecated method in that the default provider is
     * used - not "BC".
     * </p>
     */
public X509Certificate generate(PrivateKey key, SecureRandom random) throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
    TBSCertificate tbsCert = generateTbsCert();
    byte[] signature;
    try {
        signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCert);
    } catch (IOException e) {
        throw new ExtCertificateEncodingException("exception encoding TBS cert", e);
    }
    try {
        return generateJcaObject(tbsCert, signature);
    } catch (CertificateParsingException e) {
        throw new ExtCertificateEncodingException("exception producing certificate object", e);
    }
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 7 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project robovm by robovm.

the class X509V3CertificateGenerator method generate.

/**
     * generate an X509 certificate, based on the current issuer and subject,
     * using the passed in provider for the signing and the supplied source
     * of randomness, if required.
     */
public X509Certificate generate(PrivateKey key, String provider, SecureRandom random) throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
    TBSCertificate tbsCert = generateTbsCert();
    byte[] signature;
    try {
        signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCert);
    } catch (IOException e) {
        throw new ExtCertificateEncodingException("exception encoding TBS cert", e);
    }
    try {
        return generateJcaObject(tbsCert, signature);
    } catch (CertificateParsingException e) {
        throw new ExtCertificateEncodingException("exception producing certificate object", e);
    }
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 8 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project android_frameworks_base by crdroidandroid.

the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithFakeSignature.

@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithFakeSignature(PublicKey publicKey) throws IOException, CertificateParsingException {
    V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator();
    ASN1ObjectIdentifier sigAlgOid;
    AlgorithmIdentifier sigAlgId;
    byte[] signature;
    switch(mKeymasterAlgorithm) {
        case KeymasterDefs.KM_ALGORITHM_EC:
            sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid);
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(0));
            signature = new DERSequence().getEncoded();
            break;
        case KeymasterDefs.KM_ALGORITHM_RSA:
            sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
            signature = new byte[1];
            break;
        default:
            throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm);
    }
    try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) {
        tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
    }
    tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber()));
    X509Principal subject = new X509Principal(mSpec.getCertificateSubject().getEncoded());
    tbsGenerator.setSubject(subject);
    tbsGenerator.setIssuer(subject);
    tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore()));
    tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter()));
    tbsGenerator.setSignature(sigAlgId);
    TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate();
    ASN1EncodableVector result = new ASN1EncodableVector();
    result.add(tbsCertificate);
    result.add(sigAlgId);
    result.add(new DERBitString(signature));
    return new X509CertificateObject(Certificate.getInstance(new DERSequence(result)));
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ProviderException(java.security.ProviderException) Time(com.android.org.bouncycastle.asn1.x509.Time) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) ASN1Integer(com.android.org.bouncycastle.asn1.ASN1Integer) AlgorithmIdentifier(com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERInteger(com.android.org.bouncycastle.asn1.DERInteger) DERSequence(com.android.org.bouncycastle.asn1.DERSequence) X509CertificateObject(com.android.org.bouncycastle.jce.provider.X509CertificateObject) X509Principal(com.android.org.bouncycastle.jce.X509Principal) ASN1EncodableVector(com.android.org.bouncycastle.asn1.ASN1EncodableVector) V3TBSCertificateGenerator(com.android.org.bouncycastle.asn1.x509.V3TBSCertificateGenerator) TBSCertificate(com.android.org.bouncycastle.asn1.x509.TBSCertificate) ASN1ObjectIdentifier(com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 9 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project xipki by xipki.

the class ImportCrl method addCertificate.

private void addCertificate(AtomicLong maxId, int caId, Certificate cert, String profileName, String certLogId) throws DataAccessException, ImportCrlException {
    // not issued by the given issuer
    if (!caSubject.equals(cert.getIssuer())) {
        LOG.warn("certificate {} is not issued by the given CA, ignore it", certLogId);
        return;
    }
    // we don't use the binary read from file, since it may contains redundant ending bytes.
    byte[] encodedCert;
    try {
        encodedCert = cert.getEncoded();
    } catch (IOException ex) {
        throw new ImportCrlException("could not encode certificate {}" + certLogId, ex);
    }
    String b64CertHash = certhashAlgo.base64Hash(encodedCert);
    if (caSpki != null) {
        byte[] aki = null;
        try {
            aki = X509Util.extractAki(cert);
        } catch (CertificateEncodingException ex) {
            LogUtil.error(LOG, ex, "invalid AuthorityKeyIdentifier of certificate {}" + certLogId + ", ignore it");
            return;
        }
        if (aki == null || !Arrays.equals(caSpki, aki)) {
            LOG.warn("certificate {} is not issued by the given CA, ignore it", certLogId);
            return;
        }
    }
    // end if
    LOG.info("Importing certificate {}", certLogId);
    Long id = getId(caId, cert.getSerialNumber().getPositiveValue());
    boolean tblCertIdExists = (id != null);
    PreparedStatement ps;
    String sql;
    // first update the table CERT
    if (tblCertIdExists) {
        sql = SQL_UPDATE_CERT;
        ps = psUpdateCert;
    } else {
        sql = SQL_INSERT_CERT;
        ps = psInsertCert;
        id = maxId.incrementAndGet();
    }
    try {
        int offset = 1;
        if (sql == SQL_INSERT_CERT) {
            ps.setLong(offset++, id);
            // ISSUER ID IID
            ps.setInt(offset++, caId);
            // serial number SN
            ps.setString(offset++, cert.getSerialNumber().getPositiveValue().toString(16));
            // whether revoked REV
            ps.setInt(offset++, 0);
            // revocation reason RR
            ps.setNull(offset++, Types.SMALLINT);
            // revocation time RT
            ps.setNull(offset++, Types.BIGINT);
            ps.setNull(offset++, Types.BIGINT);
        }
        // last update LUPDATE
        ps.setLong(offset++, System.currentTimeMillis() / 1000);
        TBSCertificate tbsCert = cert.getTBSCertificate();
        // not before NBEFORE
        ps.setLong(offset++, tbsCert.getStartDate().getDate().getTime() / 1000);
        // not after NAFTER
        ps.setLong(offset++, tbsCert.getEndDate().getDate().getTime() / 1000);
        // profile name PN
        if (StringUtil.isBlank(profileName)) {
            ps.setNull(offset++, Types.VARCHAR);
        } else {
            ps.setString(offset++, profileName);
        }
        ps.setString(offset++, b64CertHash);
        if (sql == SQL_UPDATE_CERT) {
            ps.setLong(offset++, id);
        }
        ps.executeUpdate();
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    }
    // it is not required to add entry to table CRAW
    LOG.info("Imported  certificate {}", certLogId);
}
Also used : SQLException(java.sql.SQLException) AtomicLong(java.util.concurrent.atomic.AtomicLong) CertificateEncodingException(java.security.cert.CertificateEncodingException) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 10 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project pac4j by pac4j.

the class SAML2ClientConfiguration method createSelfSignedCert.

/**
 * Generate a self-signed certificate for dn using the provided signature algorithm and key pair.
 *
 * @param dn X.500 name to associate with certificate issuer/subject.
 * @param sigName name of the signature algorithm to use.
 * @param sigAlgID algorithm ID associated with the signature algorithm name.
 * @param keyPair the key pair to associate with the certificate.
 * @return an X509Certificate containing the public key in keyPair.
 * @throws Exception
 */
private X509Certificate createSelfSignedCert(X500Name dn, String sigName, AlgorithmIdentifier sigAlgID, KeyPair keyPair) throws Exception {
    V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));
    final Calendar c = Calendar.getInstance();
    c.setTime(new Date());
    c.add(Calendar.YEAR, 1);
    certGen.setEndDate(new Time(c.getTime()));
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
    Signature sig = Signature.getInstance(sigName);
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));
    TBSCertificate tbsCert = certGen.generateTBSCertificate();
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));
    X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    // check the certificate - this will confirm the encoded sig algorithm ID is correct.
    cert.verify(keyPair.getPublic());
    return cert;
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) ByteArrayInputStream(java.io.ByteArrayInputStream) Calendar(java.util.Calendar) Signature(java.security.Signature) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) V3TBSCertificateGenerator(org.bouncycastle.asn1.x509.V3TBSCertificateGenerator) Time(org.bouncycastle.asn1.x509.Time) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Aggregations

IOException (java.io.IOException)22 TBSCertificate (org.bouncycastle.asn1.x509.TBSCertificate)22 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 CertificateException (java.security.cert.CertificateException)7 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)6 DERSequence (com.github.zhenwei.core.asn1.DERSequence)6 ByteArrayInputStream (java.io.ByteArrayInputStream)6 CertificateEncodingException (java.security.cert.CertificateEncodingException)6 X509Certificate (java.security.cert.X509Certificate)6 DEROctetString (org.bouncycastle.asn1.DEROctetString)6 ASN1EncodableVector (com.android.org.bouncycastle.asn1.ASN1EncodableVector)5 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)5 ASN1Integer (com.android.org.bouncycastle.asn1.ASN1Integer)5 ASN1ObjectIdentifier (com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier)5 DERBitString (com.android.org.bouncycastle.asn1.DERBitString)5 DERInteger (com.android.org.bouncycastle.asn1.DERInteger)5 DERSequence (com.android.org.bouncycastle.asn1.DERSequence)5 AlgorithmIdentifier (com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier)5 TBSCertificate (com.android.org.bouncycastle.asn1.x509.TBSCertificate)5 Time (com.android.org.bouncycastle.asn1.x509.Time)5