Example usage for java.security.cert X509Certificate getSerialNumber

List of usage examples for java.security.cert X509Certificate getSerialNumber

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSerialNumber.

Prototype

public abstract BigInteger getSerialNumber();

Source Link

Document

Gets the serialNumber value from the certificate.

Usage

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateManagementServiceImplTests.java

@Test(description = "This test case tests deleting Certificate from the keystore")
public void testRemoveCertificate() throws CertificateManagementException, KeystoreException {
    X509Certificate x509Certificate = managementService.generateX509Certificate();
    List<CertificateResponse> certificates = managementService.getCertificates();
    int size = certificates.size();
    boolean removed = managementService.removeCertificate(x509Certificate.getSerialNumber().toString());
    certificates = managementService.getCertificates();
    int sizeAfter = certificates.size();
    Assert.assertNotNull(removed);/*from   w  w w  .j ava 2 s . c  o  m*/
    Assert.assertTrue(removed);
    Assert.assertEquals((size - 1), sizeAfter);
    log.info("RemoveCertificate Test Successful");
}

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

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {/*  w w  w . j a  v  a 2 s  .c  o  m*/

        CAdESSignature signature = new CAdESSignature(byteArray);
        assertNotNull(signature.getCmsSignedData());

        ASN1InputStream asn1sInput = new ASN1InputStream(byteArray);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        assertEquals(2, asn1Seq.size());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);
        logger.info("OID : " + oid.toString());

        ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(asn1Seq.getObjectAt(1));

        logger.info("TAGGED OBJ : " + taggedObj.toString());

        ASN1Primitive object = taggedObj.getObject();
        logger.info("OBJ : " + object.toString());

        SignedData signedData = SignedData.getInstance(object);
        logger.info("SIGNED DATA : " + signedData.toString());

        ASN1Set digestAlgorithms = signedData.getDigestAlgorithms();
        logger.info("DIGEST ALGOS : " + digestAlgorithms.toString());

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        logger.info("ENCAPSULATED CONTENT INFO : " + encapContentInfo.getContentType() + " "
                + encapContentInfo.getContent());

        ASN1Set certificates = signedData.getCertificates();
        logger.info("CERTIFICATES (" + certificates.size() + ") : " + certificates);

        List<X509Certificate> foundCertificates = new ArrayList<X509Certificate>();
        for (int i = 0; i < certificates.size(); i++) {
            ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i));
            logger.info("SEQ cert " + i + " : " + seqCertif);

            X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded());
            X509Certificate certificate = new JcaX509CertificateConverter()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);

            certificate.checkValidity();

            logger.info("Cert " + i + " : " + certificate);

            foundCertificates.add(certificate);
        }

        ASN1Set crLs = signedData.getCRLs();
        logger.info("CRLs : " + crLs);

        ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
        logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
        assertEquals(1, signerInfosAsn1.size());

        ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0));

        SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo);
        logger.info("SIGNER INFO : " + signedInfo.toString());

        SignerIdentifier sid = signedInfo.getSID();
        logger.info("SIGNER IDENTIFIER : " + sid.getId());

        IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(signedInfo.getSID());
        logger.info("ISSUER AND SN : " + issuerAndSerialNumber.toString());

        BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();

        X509Certificate signerCertificate = null;
        for (X509Certificate x509Certificate : foundCertificates) {
            // TODO check issuer name
            if (serial.equals(x509Certificate.getSerialNumber())) {
                signerCertificate = x509Certificate;
            }
        }
        assertNotNull(signerCertificate);

        ASN1OctetString encryptedDigest = signedInfo.getEncryptedDigest();
        logger.info("ENCRYPT DIGEST : " + encryptedDigest.toString());

        ASN1Sequence seq = ASN1Sequence.getInstance(object);

        ASN1Integer version = ASN1Integer.getInstance(seq.getObjectAt(0));
        logger.info("VERSION : " + version.toString());

        ASN1Set digestManualSet = ASN1Set.getInstance(seq.getObjectAt(1));
        logger.info("DIGEST SET : " + digestManualSet.toString());
        assertEquals(digestAlgorithms, digestManualSet);

        ASN1Sequence seqDigest = ASN1Sequence.getInstance(digestManualSet.getObjectAt(0));
        // assertEquals(1, seqDigest.size());

        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier.getInstance(seqDigest.getObjectAt(0));
        assertEquals(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()), oidDigestAlgo);

        ASN1Sequence seqEncapsulatedInfo = ASN1Sequence.getInstance(seq.getObjectAt(2));
        logger.info("ENCAPSULATED INFO : " + seqEncapsulatedInfo.toString());

        ASN1ObjectIdentifier oidContentType = ASN1ObjectIdentifier
                .getInstance(seqEncapsulatedInfo.getObjectAt(0));
        logger.info("OID CONTENT TYPE : " + oidContentType.toString());

        ASN1TaggedObject taggedContent = DERTaggedObject.getInstance(seqEncapsulatedInfo.getObjectAt(1));

        ASN1OctetString contentOctetString = ASN1OctetString.getInstance(taggedContent.getObject());
        String content = new String(contentOctetString.getOctets());
        assertEquals(HELLO_WORLD, content);
        logger.info("CONTENT : " + content);

        byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA256, HELLO_WORLD.getBytes());
        String encodeHexDigest = Hex.toHexString(digest);
        logger.info("CONTENT DIGEST COMPUTED : " + encodeHexDigest);

        ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes();
        logger.info("AUTHENTICATED ATTRIBUTES : " + authenticatedAttributes.toString());

        // ASN1Sequence seqAuthAttrib = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(0));

        logger.info("Nb Auth Attributes : " + authenticatedAttributes.size());

        String embeddedDigest = StringUtils.EMPTY;
        for (int i = 0; i < authenticatedAttributes.size(); i++) {
            ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i));
            logger.info(authAttrSeq.toString());
            ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0));
            if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attrOid)) {
                ASN1Set setMessageDigest = ASN1Set.getInstance(authAttrSeq.getObjectAt(1));
                ASN1OctetString asn1ObjString = ASN1OctetString.getInstance(setMessageDigest.getObjectAt(0));
                embeddedDigest = Hex.toHexString(asn1ObjString.getOctets());
            }
        }
        assertEquals(encodeHexDigest, embeddedDigest);

        ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
        String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

        logger.info("SIGNATURE VALUE : " + signatureValue);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
        byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

        ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

        ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
        logger.info("Decrypted : " + seqDecrypt);

        DigestInfo digestInfo = new DigestInfo(seqDecrypt);
        assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

        String decryptedDigestEncodeBase64 = Base64.encode(digestInfo.getDigest());
        logger.info("Decrypted Base64 : " + decryptedDigestEncodeBase64);

        byte[] encoded = signedInfo.getAuthenticatedAttributes().getEncoded();
        MessageDigest messageDigest = MessageDigest.getInstance(DigestAlgorithm.SHA256.getName());
        byte[] digestOfAuthenticatedAttributes = messageDigest.digest(encoded);

        String computedDigestEncodeBase64 = Base64.encode(digestOfAuthenticatedAttributes);
        logger.info("Computed Base64 : " + computedDigestEncodeBase64);

        assertEquals(decryptedDigestEncodeBase64, computedDigestEncodeBase64);

        IOUtils.closeQuietly(asn1sInput);
        IOUtils.closeQuietly(inputDecrypted);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

From source file:mx.bigdata.sat.cfd.CFDv2.java

public void sellar(PrivateKey key, X509Certificate cert) throws Exception {
    cert.checkValidity();/*from  ww  w .j a v a2  s.c o  m*/
    String signature = getSignature(key);
    document.setSello(signature);
    byte[] bytes = cert.getEncoded();
    Base64 b64 = new Base64(-1);
    String certStr = b64.encodeToString(bytes);
    document.setCertificado(certStr);
    BigInteger bi = cert.getSerialNumber();
    document.setNoCertificado(new String(bi.toByteArray()));
}

From source file:mitm.common.security.crl.GenerateTestCRLs.java

@Test
public void testGenerateCACRLSignedByIncorrectKey() throws Exception {
    X509CRLBuilder crlGenerator = createX509CRLBuilder();

    Date thisDate = TestUtils.parseDate("30-Nov-2007 11:38:35 GMT");

    Date nextDate = TestUtils.parseDate("30-Nov-2027 11:38:35 GMT");

    crlGenerator.setThisUpdate(thisDate);
    crlGenerator.setNextUpdate(nextDate);
    crlGenerator.setSignatureAlgorithm("SHA256WithRSAEncryption");

    X509Certificate certificate = TestUtils
            .loadCertificate("test/resources/testdata/certificates/" + "valid_certificate_mitm_test_ca.cer");
    assertNotNull(certificate);//  w ww . j a  v  a  2  s  . co  m

    crlGenerator.addCRLEntry(certificate.getSerialNumber(), thisDate, CRLReason.privilegeWithdrawn);

    String encodedPrivateKey = "30820276020100300d06092a864886f70d0101010500048202603082025c"
            + "02010002818100a9fee3017954c99b248d1486830c71b2e0ea3f9b7a2763"
            + "1bed8a731f5bd7e1edf856bc3fb7c63dedbeb5bb0de474e7792b3aa7e7b2"
            + "274c03a47c7d89b1935eaef172c6395f2322f1ed9e61ae46d716b4b4394c"
            + "1a802db05a2d7c3d1d41a3e8afc65ff8dada7414744f1ee1540e50ee7fb8"
            + "db437b20c5ee33a82b9d575cfbc951020301000102818004f84ab2b45562"
            + "3f82e60cff91bd3f65b765a1ce6dd7d0f1f413e421ba91a92d47e161478b"
            + "9be41b9b43bce03f199bdad304b7fbf21d6bff7f439477fe150ce38c312f"
            + "c015f3c89291aaa42c4c106f623dfd9f76acad2f1c77b590f038ffbb25f9"
            + "14b6f7ead769808ddd0e2d648442620b50518d9b7fb132b2fa1fa3e9d628"
            + "41024100e69ab3765120d0e0ba5dc21bf384b2f553211b4b1902175454c6"
            + "2f1b0f8ad385d78490539308c9fd5145ae36cc2a6d364fdd97d83d9b6623"
            + "a987db239e716055024100bcb77acf1e9829ab5b2c9a5e73d343db857474"
            + "a529ba52ca256655eb7d760e85d3c68eec9500e3db0494c8f77cb8058593"
            + "6e52a9290149367392d74ecdc3510d024100bd15723b7cb024b56ffabad3"
            + "c26c3774f2b1bdb8690c0ee7060feec6088b737f56450b368be4740332e5"
            + "a8c0a3cdd1f8eba9adfd101ee0b43329036584604075024055465b9a27ea"
            + "fe394e33b375a6c4fa4ec1d943b4364cd9883aaa297d05ee48d5b4426ee6"
            + "fcd5b02091cb619c63a10bedb6170e071e5e5464e4889ffe1e007a290240"
            + "7b60d23994a2ec38db909678446ed56d32455bf684141b9ee0aec68b2025"
            + "1d4d94fd2beebf02074559b811ae1130d2e2aa3bec2e9bccb06969104856" + "00c70759";

    PrivateKey privateKey = decodePrivateKey(encodedPrivateKey);

    // sign not by the caPrivateKey but by some other key
    X509CRL crl = crlGenerator.generateCRL(new KeyAndCertificateImpl(privateKey, caCertificate));

    assertEquals("EMAILADDRESS=ca@example.com, CN=MITM Test CA, L=Amsterdam, ST=NH, C=NL",
            crl.getIssuerX500Principal().toString());
    assertEquals(thisDate, crl.getThisUpdate());
    assertEquals(nextDate, crl.getNextUpdate());
    assertEquals(1, crl.getRevokedCertificates().size());
    assertTrue(crl.isRevoked(certificate));

    File crlFile = new File("test/tmp/test-generate-ca-signed-incorrect-key.crl");

    FileOutputStream fos = new FileOutputStream(crlFile);

    IOUtils.write(crl.getEncoded(), fos);

    fos.close();
}

From source file:org.votingsystem.web.ejb.SignatureBean.java

public void addCertAuthority(CertificateVS certificateVS) throws Exception {
    X509Certificate x509Cert = certificateVS.getX509Cert();
    trustedCerts.add(x509Cert);/* w  w w  .  jav  a  2s.c  o  m*/
    trustedCertsHashMap.put(x509Cert.getSerialNumber().longValue(), certificateVS);
    trustAnchors.add(new TrustAnchor(x509Cert, null));
    log.info("certificateVS.id: " + certificateVS.getId() + " - " + x509Cert.getSubjectDN()
            + " - num. trustedCerts: " + trustedCerts.size());
}

From source file:org.ejbca.core.protocol.cmp.CrmfRARequestTest.java

public void test02NullKeyID() throws Exception {

    // Create a new good user

    String userDN = "CN=keyIDTestUser,C=SE";
    final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    final int reqId;

    final PKIMessage one = genCertReq(issuerDN, userDN, keys, cacert, nonce, transid, true, null, null, null,
            null);/*from  ww  w.j ava 2s  . c o  m*/
    final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, null, 567);
    Assert.assertNotNull(req);
    reqId = req.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200);
    // do not check signing if we expect a failure (sFailMessage==null)
    checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, true, null);
    X509Certificate cert = checkCmpCertRepMessage(userDN, cacert, resp, reqId);
    BigInteger serialnumber = cert.getSerialNumber();

    // Revoke the created certificate
    //final String hash = "foo123";
    final PKIMessage con = genRevReq(issuerDN, userDN, serialnumber, cacert, nonce, transid, false);
    Assert.assertNotNull(con);
    PKIMessage revmsg = protectPKIMessage(con, false, PBEPASSWORD, null, 567);
    final ByteArrayOutputStream baorev = new ByteArrayOutputStream();
    final DEROutputStream outrev = new DEROutputStream(baorev);
    outrev.writeObject(revmsg);
    final byte[] barev = baorev.toByteArray();
    // Send request and receive response
    final byte[] resprev = sendCmpHttp(barev, 200);
    checkCmpResponseGeneral(resprev, issuerDN, userDN, cacert, nonce, transid, false, null);
    int revstatus = checkRevokeStatus(issuerDN, serialnumber);
    Assert.assertEquals("Certificate revocation failed.", RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE,
            revstatus);

}

From source file:netscape.security.pkcs.PKCS7.java

/**
 * Returns the X.509 certificate listed in this PKCS7 block
 * which has a matching serial number and Issuer name, or
 * null if one is not found.// w w w  .  j  av a  2s .  c om
 *
 * @param serial the serial number of the certificate to retrieve.
 * @param name the Distinguished Name of the Issuer.
 */
public X509Certificate getCertificate(BigInt serial, X500Name name) {

    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        X500Name thisName = (X500Name) cert.getIssuerDN();
        BigInteger tmpSerial = cert.getSerialNumber();
        BigInt thisSerial = new BigInt(tmpSerial);
        if (serial.equals(thisSerial) && name.equals(thisName)) {
            return cert;
        }
    }
    return null;
}

From source file:edu.vt.middleware.crypt.KeyStoreCli.java

/**
 * Prints a string representation of the given certificate to STDOUT. For an
 * X.509 certificate, prints important fields.
 *
 * @param  cert  Certificate to print.//from  w  w  w . jav a  2s.c o  m
 *
 * @throws  Exception  On print errors.
 */
protected void printCertificate(final Certificate cert) throws Exception {
    if (cert instanceof X509Certificate) {
        final X509Certificate xCert = (X509Certificate) cert;
        final byte[] encodedCert = xCert.getEncoded();
        System.out.println("Subject: " + xCert.getSubjectDN());
        System.out.println("Issuer: " + xCert.getIssuerDN());
        System.out.println("Serial: " + hexConv.fromBytes(xCert.getSerialNumber().toByteArray()));
        System.out.println("Valid not before: " + xCert.getNotBefore());
        System.out.println("Valid not after: " + xCert.getNotAfter());
        System.out.println("MD5 fingerprint: " + md5.digest(encodedCert, hexConv));
        System.out.println("SHA1 fingerprint: " + sha1.digest(encodedCert, hexConv));
    } else {
        System.out.println(cert);
    }
}

From source file:org.ejbca.core.protocol.ocsp.extension.unid.OCSPUnidExtension.java

private boolean checkAuthorization(X509Certificate[] certificates, String remoteAddress, String remoteHost) {

    if (certificates == null) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoclientauth", remoteAddress, remoteHost);
        m_log.error(errMsg);// www .j  a  v  a  2 s .c  o  m
        return false;
    }
    // The certificate of the entity is nr 0
    X509Certificate cert = certificates[0];
    if (cert == null) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoclientauth", remoteAddress, remoteHost);
        m_log.error(errMsg);
        return false;
    }
    // Check if the certificate is authorised to access the Fnr
    if (this.trustedCerts.contains(cert.getSerialNumber())) {
        // If we found in the hashmap the same key with issuer and serialnumber, we know we got it. 
        // Just verify it as well to be damn sure
        try {
            cert.verify(this.cacert.getPublicKey());
        } catch (Exception e) {
            String errMsg = intres.getLocalizedMessage("ocsp.errorverifycert");
            m_log.error(errMsg, e);
            return false;
        }
        // If verify was successful we know if was good!
        return true;
    }
    String errMsg = intres.getLocalizedMessage("ocsp.erroruntrustedclientauth", remoteAddress, remoteHost);
    m_log.error(errMsg);
    return false;
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * To get the unique identifier(serialnumber_issuerdn) of the certificate.
 *
 * @param certificate Base64 encoded certificate.
 * @return unique identifier of the certification.
 *//*  w w  w.  ja va  2  s .c o  m*/
public String getUniqueIdentifierOfCertificate(String certificate) {
    byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
    ByteArrayInputStream serverCert = new ByteArrayInputStream(cert);
    String uniqueIdentifier = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        while (serverCert.available() > 0) {
            Certificate generatedCertificate = cf.generateCertificate(serverCert);
            X509Certificate x509Certificate = (X509Certificate) generatedCertificate;
            uniqueIdentifier = String
                    .valueOf(x509Certificate.getSerialNumber() + "_" + x509Certificate.getIssuerDN());
            uniqueIdentifier = uniqueIdentifier.replaceAll(",", "#").replaceAll("\"", "'");
        }
    } catch (CertificateException e) {
        log.error("Error while getting serial number of the certificate.", e);
    } finally {
        closeStreams(serverCert);
    }
    return uniqueIdentifier;
}