Search in sources :

Example 76 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project nhin-d by DirectProject.

the class MessageSigInspector method main.

public static void main(String[] args) {
    if (args.length == 0) {
        //printUsage();
        System.exit(-1);
    }
    String messgefile = null;
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        // Options
        if (!arg.startsWith("-")) {
            System.err.println("Error: Unexpected argument [" + arg + "]\n");
            //printUsage();
            System.exit(-1);
        } else if (arg.equalsIgnoreCase("-msgFile")) {
            if (i == args.length - 1 || args[i + 1].startsWith("-")) {
                System.err.println("Error: Missing message file");
                System.exit(-1);
            }
            messgefile = args[++i];
        } else if (arg.equals("-help")) {
            //printUsage();
            System.exit(-1);
        } else {
            System.err.println("Error: Unknown argument " + arg + "\n");
            //printUsage();
            System.exit(-1);
        }
    }
    if (messgefile == null) {
        System.err.println("Error: missing message file\n");
    }
    InputStream inStream = null;
    try {
        inStream = FileUtils.openInputStream(new File(messgefile));
        MimeMessage message = new MimeMessage(null, inStream);
        MimeMultipart mm = (MimeMultipart) message.getContent();
        //byte[] messageBytes = EntitySerializer.Default.serializeToBytes(mm.getBodyPart(0).getContent());
        //MimeBodyPart signedContent = null;
        //signedContent = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
        final CMSSignedData signed = new CMSSignedData(new CMSProcessableBodyPart(mm.getBodyPart(0)), mm.getBodyPart(1).getInputStream());
        CertStore certs = signed.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
        SignerInformationStore signers = signed.getSignerInfos();
        @SuppressWarnings("unchecked") Collection<SignerInformation> c = signers.getSigners();
        System.out.println("Found " + c.size() + " signers");
        int cnt = 1;
        for (SignerInformation signer : c) {
            Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID());
            if (certCollection != null && certCollection.size() > 0) {
                X509Certificate cert = (X509Certificate) certCollection.iterator().next();
                System.out.println("\r\nInfo for certificate " + cnt++);
                System.out.println("\tSubject " + cert.getSubjectDN());
                FileUtils.writeByteArrayToFile(new File("SigCert.der"), cert.getEncoded());
                byte[] bytes = cert.getExtensionValue("2.5.29.15");
                if (bytes != null) {
                    final DERObject obj = getObject(bytes);
                    final KeyUsage keyUsage = new KeyUsage((DERBitString) obj);
                    final byte[] data = keyUsage.getBytes();
                    final int intValue = (data.length == 1) ? data[0] & 0xff : (data[1] & 0xff) << 8 | (data[0] & 0xff);
                    System.out.println("\tKey Usage: " + intValue);
                } else
                    System.out.println("\tKey Usage: NONE");
                //verify and get the digests
                final Attribute digAttr = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
                final DERObject hashObj = digAttr.getAttrValues().getObjectAt(0).getDERObject();
                final byte[] signedDigest = ((ASN1OctetString) hashObj).getOctets();
                final String signedDigestHex = org.apache.commons.codec.binary.Hex.encodeHexString(signedDigest);
                System.out.println("\r\nSigned Message Digest: " + signedDigestHex);
                try {
                    signer.verify(cert, "BC");
                    System.out.println("Signature verified.");
                } catch (CMSException e) {
                    System.out.println("Signature failed to verify.");
                }
                // should have the computed digest now
                final byte[] digest = signer.getContentDigest();
                final String digestHex = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
                System.out.println("\r\nComputed Message Digest: " + digestHex);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(inStream);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) Attribute(org.bouncycastle.asn1.cms.Attribute) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) InputStream(java.io.InputStream) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) SignerInformation(org.bouncycastle.cms.SignerInformation) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CMSException(org.bouncycastle.cms.CMSException) PolicyProcessException(org.nhindirect.policy.PolicyProcessException) CMSProcessableBodyPart(org.bouncycastle.mail.smime.CMSProcessableBodyPart) DERObject(org.bouncycastle.asn1.DERObject) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) File(java.io.File) CertStore(java.security.cert.CertStore) CMSException(org.bouncycastle.cms.CMSException)

Example 77 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project XobotOS by xamarin.

the class CertPathValidatorUtilities method getNextWorkingKey.

/**
     * Return the next working key inheriting DSA parameters if necessary.
     * <p>
     * This methods inherits DSA parameters from the indexed certificate or
     * previous certificates in the certificate chain to the returned
     * <code>PublicKey</code>. The list is searched upwards, meaning the end
     * certificate is at position 0 and previous certificates are following.
     * </p>
     * <p>
     * If the indexed certificate does not contain a DSA key this method simply
     * returns the public key. If the DSA key already contains DSA parameters
     * the key is also only returned.
     * </p>
     * 
     * @param certs The certification path.
     * @param index The index of the certificate which contains the public key
     *            which should be extended with DSA parameters.
     * @return The public key of the certificate in list position
     *         <code>index</code> extended with DSA parameters if applicable.
     * @throws AnnotatedException if DSA parameters cannot be inherited.
     */
protected static PublicKey getNextWorkingKey(List certs, int index) throws CertPathValidatorException {
    Certificate cert = (Certificate) certs.get(index);
    PublicKey pubKey = cert.getPublicKey();
    if (!(pubKey instanceof DSAPublicKey)) {
        return pubKey;
    }
    DSAPublicKey dsaPubKey = (DSAPublicKey) pubKey;
    if (dsaPubKey.getParams() != null) {
        return dsaPubKey;
    }
    for (int i = index + 1; i < certs.size(); i++) {
        X509Certificate parentCert = (X509Certificate) certs.get(i);
        pubKey = parentCert.getPublicKey();
        if (!(pubKey instanceof DSAPublicKey)) {
            throw new CertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
        }
        DSAPublicKey prevDSAPubKey = (DSAPublicKey) pubKey;
        if (prevDSAPubKey.getParams() == null) {
            continue;
        }
        DSAParams dsaParams = prevDSAPubKey.getParams();
        DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec(dsaPubKey.getY(), dsaParams.getP(), dsaParams.getQ(), dsaParams.getG());
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("DSA", BouncyCastleProvider.PROVIDER_NAME);
            return keyFactory.generatePublic(dsaPubKeySpec);
        } catch (Exception exception) {
            throw new RuntimeException(exception.getMessage());
        }
    }
    throw new CertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
}
Also used : CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) PublicKey(java.security.PublicKey) DSAPublicKey(java.security.interfaces.DSAPublicKey) DSAParams(java.security.interfaces.DSAParams) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) X509Certificate(java.security.cert.X509Certificate) KeyFactory(java.security.KeyFactory) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ParseException(java.text.ParseException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertStoreException(java.security.cert.CertStoreException) CertificateParsingException(java.security.cert.CertificateParsingException) StoreException(org.bouncycastle.util.StoreException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) X509AttributeCertificate(org.bouncycastle.x509.X509AttributeCertificate) DSAPublicKey(java.security.interfaces.DSAPublicKey) DSAPublicKeySpec(java.security.spec.DSAPublicKeySpec)

Example 78 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project oxAuth by GluuFederation.

the class CRLCertificateVerifier method getCrlUri.

public String getCrlUri(X509Certificate certificate) throws IOException {
    ASN1Primitive obj;
    try {
        obj = getExtensionValue(certificate, Extension.cRLDistributionPoints.getId());
    } catch (IOException ex) {
        log.error("Failed to get CRL URL", ex);
        return null;
    }
    if (obj == null) {
        return null;
    }
    CRLDistPoint distPoint = CRLDistPoint.getInstance(obj);
    DistributionPoint[] distributionPoints = distPoint.getDistributionPoints();
    for (DistributionPoint distributionPoint : distributionPoints) {
        DistributionPointName distributionPointName = distributionPoint.getDistributionPoint();
        if (DistributionPointName.FULL_NAME != distributionPointName.getType()) {
            continue;
        }
        GeneralNames generalNames = (GeneralNames) distributionPointName.getName();
        GeneralName[] names = generalNames.getNames();
        for (GeneralName name : names) {
            if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
                continue;
            }
            DERIA5String derStr = DERIA5String.getInstance((ASN1TaggedObject) name.toASN1Primitive(), false);
            return derStr.getString();
        }
    }
    return null;
}
Also used : DERIA5String(org.bouncycastle.asn1.DERIA5String) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) IOException(java.io.IOException) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 79 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project poi by apache.

the class PkiTestUtils method createOcspResp.

public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis) throws Exception {
    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
    X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
    CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());
    // request
    //create a nonce to avoid replay attack
    BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
    DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
    Extensions exts = new Extensions(ext);
    OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    ocspReqBuilder.addRequest(certId);
    ocspReqBuilder.setRequestExtensions(exts);
    OCSPReq ocspReq = ocspReqBuilder.build();
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded());
    BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
    basicOCSPRespBuilder.setResponseExtensions(exts);
    // request processing
    Req[] requestList = ocspReq.getRequestList();
    for (Req ocspRequest : requestList) {
        CertificateID certificateID = ocspRequest.getCertID();
        CertificateStatus certificateStatus = CertificateStatus.GOOD;
        if (revoked) {
            certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
        }
        basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
    }
    // basic response generation
    X509CertificateHolder[] chain = null;
    if (!ocspResponderCertificate.equals(issuerCertificate)) {
        // TODO: HorribleProxy can't convert array input params yet
        chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), issuerHolder };
    }
    ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(ocspResponderPrivateKey);
    BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));
    OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
    OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);
    return ocspResp;
}
Also used : BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) OCSPRespBuilder(org.bouncycastle.cert.ocsp.OCSPRespBuilder) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DEROctetString(org.bouncycastle.asn1.DEROctetString) Date(java.util.Date) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) Extension(org.bouncycastle.asn1.x509.Extension) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) Req(org.bouncycastle.cert.ocsp.Req) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq)

Example 80 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project poi by apache.

the class TestSignatureInfo method initKeyPair.

private void initKeyPair(String alias, String subjectDN) throws Exception {
    final char[] password = "test".toCharArray();
    File file = new File("build/test.pfx");
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    if (file.exists()) {
        FileInputStream fis = new FileInputStream(file);
        keystore.load(fis, password);
        fis.close();
    } else {
        keystore.load(null, password);
    }
    if (keystore.isKeyEntry(alias)) {
        Key key = keystore.getKey(alias, password);
        x509 = (X509Certificate) keystore.getCertificate(alias);
        keyPair = new KeyPair(x509.getPublicKey(), (PrivateKey) key);
    } else {
        keyPair = PkiTestUtils.generateKeyPair();
        Date notBefore = cal.getTime();
        Calendar cal2 = (Calendar) cal.clone();
        cal2.add(Calendar.YEAR, 1);
        Date notAfter = cal2.getTime();
        KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature);
        x509 = PkiTestUtils.generateCertificate(keyPair.getPublic(), subjectDN, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, keyUsage);
        keystore.setKeyEntry(alias, keyPair.getPrivate(), password, new Certificate[] { x509 });
        FileOutputStream fos = new FileOutputStream(file);
        keystore.store(fos, password);
        fos.close();
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) Calendar(java.util.Calendar) FileOutputStream(java.io.FileOutputStream) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) File(java.io.File) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) Key(java.security.Key) PrivateKey(java.security.PrivateKey) Date(java.util.Date)

Aggregations

IOException (java.io.IOException)242 X509Certificate (java.security.cert.X509Certificate)216 Date (java.util.Date)133 X500Name (org.bouncycastle.asn1.x500.X500Name)133 BigInteger (java.math.BigInteger)120 ContentSigner (org.bouncycastle.operator.ContentSigner)102 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)101 GeneralName (org.bouncycastle.asn1.x509.GeneralName)100 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)96 CertificateException (java.security.cert.CertificateException)95 ArrayList (java.util.ArrayList)90 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)85 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)82 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)78 GeneralSecurityException (java.security.GeneralSecurityException)69 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)62 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)62 Extension (org.bouncycastle.asn1.x509.Extension)61 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)60 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)59