Search in sources :

Example 91 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project jruby-openssl by jruby.

the class OCSPBasicResponse method verify.

@JRubyMethod(name = "verify", rest = true)
public IRubyObject verify(final ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.runtime;
    int flags = 0;
    IRubyObject certificates = args[0];
    IRubyObject store = args[1];
    boolean ret = false;
    if (Arity.checkArgumentCount(runtime, args, 2, 3) == 3) {
        flags = RubyFixnum.fix2int(args[2]);
    }
    JcaContentVerifierProviderBuilder jcacvpb = new JcaContentVerifierProviderBuilder();
    jcacvpb.setProvider("BC");
    BasicOCSPResp basicOCSPResp = getBasicOCSPResp();
    java.security.cert.Certificate signer = findSignerCert(context, asn1BCBasicOCSPResp, convertRubyCerts(certificates), flags);
    if (signer == null)
        return RubyBoolean.newBoolean(runtime, false);
    if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOINTERN))) == 0 && (flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_TRUSTOTHER))) != 0) {
        flags |= RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOVERIFY));
    }
    if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOSIGS))) == 0) {
        PublicKey sPKey = signer.getPublicKey();
        if (sPKey == null)
            return RubyBoolean.newBoolean(runtime, false);
        try {
            ContentVerifierProvider cvp = jcacvpb.build(sPKey);
            ret = basicOCSPResp.isSignatureValid(cvp);
        } catch (Exception e) {
            throw newOCSPError(runtime, e);
        }
    }
    if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOVERIFY))) == 0) {
        List<X509Cert> untrustedCerts = null;
        if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCHAIN))) != 0) {
        } else if (basicOCSPResp.getCerts() != null && (certificates != null && !((RubyArray) certificates).isEmpty())) {
            untrustedCerts = getCertsFromResp();
            Iterator<java.security.cert.Certificate> certIt = ((RubyArray) certificates).iterator();
            while (certIt.hasNext()) {
                try {
                    untrustedCerts.add(X509Cert.wrap(context, certIt.next().getEncoded()));
                } catch (CertificateEncodingException e) {
                    throw newOCSPError(runtime, e);
                }
            }
        } else {
            untrustedCerts = getCertsFromResp();
        }
        RubyArray rUntrustedCerts = RubyArray.newEmptyArray(runtime);
        if (untrustedCerts != null) {
            X509Cert[] rubyCerts = new X509Cert[untrustedCerts.size()];
            rUntrustedCerts = RubyArray.newArray(runtime, untrustedCerts.toArray(rubyCerts));
        }
        X509StoreContext ctx;
        try {
            ctx = X509StoreContext.newStoreContext(context, (X509Store) store, X509Cert.wrap(runtime, signer), rUntrustedCerts);
        } catch (CertificateEncodingException e) {
            throw newOCSPError(runtime, e);
        }
        ctx.set_purpose(context, _X509(runtime).getConstant("PURPOSE_OCSP_HELPER"));
        ret = ctx.verify(context).isTrue();
        IRubyObject chain = ctx.chain(context);
        if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCHECKS))) > 0) {
            ret = true;
        }
        try {
            if (checkIssuer(getBasicOCSPResp(), chain))
                return RubyBoolean.newBoolean(runtime, true);
        } catch (IOException e) {
            throw newOCSPError(runtime, e);
        }
        if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCHAIN))) != 0) {
            return RubyBoolean.newBoolean(runtime, ret);
        } else {
            X509Cert rootCA = (X509Cert) ((RubyArray) chain).last();
            PublicKey rootKey = rootCA.getAuxCert().getPublicKey();
            try {
                // check if self-signed and valid (trusts itself)
                rootCA.getAuxCert().verify(rootKey);
                ret = true;
            } catch (Exception e) {
                ret = false;
            }
        }
    }
    return RubyBoolean.newBoolean(runtime, ret);
}
Also used : RubyArray(org.jruby.RubyArray) PublicKey(java.security.PublicKey) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) IRubyObject(org.jruby.runtime.builtin.IRubyObject) RubyFixnum(org.jruby.RubyFixnum) RaiseException(org.jruby.exceptions.RaiseException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) Iterator(java.util.Iterator) Ruby(org.jruby.Ruby) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) JRubyMethod(org.jruby.anno.JRubyMethod)

Example 92 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project jruby-openssl by jruby.

the class MiscPEMGenerator method createPemObject.

private PemObject createPemObject(Object o) throws IOException {
    String type;
    byte[] encoding;
    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509CertificateHolder) {
        type = "CERTIFICATE";
        encoding = ((X509CertificateHolder) o).getEncoded();
    } else if (o instanceof X509CRLHolder) {
        type = "X509 CRL";
        encoding = ((X509CRLHolder) o).getEncoded();
    } else if (o instanceof PrivateKeyInfo) {
        PrivateKeyInfo info = (PrivateKeyInfo) o;
        ASN1ObjectIdentifier algOID = info.getPrivateKeyAlgorithm().getAlgorithm();
        if (algOID.equals(PKCSObjectIdentifiers.rsaEncryption)) {
            type = "RSA PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (algOID.equals(dsaOids[0]) || algOID.equals(dsaOids[1])) {
            type = "DSA PRIVATE KEY";
            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new ASN1Integer(BigInteger.ZERO));
            v.add(new ASN1Integer(p.getP()));
            v.add(new ASN1Integer(p.getQ()));
            v.add(new ASN1Integer(p.getG()));
            BigInteger x = ASN1Integer.getInstance(info.parsePrivateKey()).getValue();
            BigInteger y = p.getG().modPow(x, p.getP());
            v.add(new ASN1Integer(y));
            v.add(new ASN1Integer(x));
            encoding = new DERSequence(v).getEncoded();
        } else if (algOID.equals(X9ObjectIdentifiers.id_ecPublicKey)) {
            type = "EC PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof SubjectPublicKeyInfo) {
        type = "PUBLIC KEY";
        encoding = ((SubjectPublicKeyInfo) o).getEncoded();
    } else if (o instanceof X509AttributeCertificateHolder) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificateHolder) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    } else // 
    if (// 1.47 compatibility
    o instanceof java.security.cert.X509Certificate) {
        type = "CERTIFICATE";
        try {
            encoding = ((java.security.cert.X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (// 1.47 compatibility
    o instanceof java.security.cert.X509CRL) {
        type = "X509 CRL";
        try {
            encoding = ((java.security.cert.X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (// 1.47 compatibility
    o instanceof java.security.KeyPair) {
        return createPemObject(((java.security.KeyPair) o).getPrivate());
    } else if (// 1.47 compatibility
    o instanceof java.security.PrivateKey) {
        PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(((java.security.Key) o).getEncoded()));
        if (o instanceof java.security.interfaces.RSAPrivateKey) {
            type = "RSA PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (o instanceof java.security.interfaces.DSAPrivateKey) {
            type = "DSA PRIVATE KEY";
            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(p.getP()));
            v.add(new DERInteger(p.getQ()));
            v.add(new DERInteger(p.getG()));
            BigInteger x = ((java.security.interfaces.DSAPrivateKey) o).getX();
            BigInteger y = p.getG().modPow(x, p.getP());
            v.add(new DERInteger(y));
            v.add(new DERInteger(x));
            encoding = new DERSequence(v).getEncoded();
        } else if (((java.security.PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (// 1.47 compatibility
    o instanceof java.security.PublicKey) {
        type = "PUBLIC KEY";
        encoding = ((java.security.PublicKey) o).getEncoded();
    } else if (// 1.47 compatibility
    o instanceof X509AttributeCertificate) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificate) o).getEncoded();
    } else // 
    // 
    // 
    {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }
    if (// NEW STUFF (NOT IN OLD)
    encryptor != null) {
        String dekAlgName = Strings.toUpperCase(encryptor.getAlgorithm());
        // Note: For backward compatibility
        if (dekAlgName.equals("DESEDE")) {
            dekAlgName = "DES-EDE3-CBC";
        }
        byte[] iv = encryptor.getIV();
        byte[] encData = encryptor.encrypt(encoding);
        List<PemHeader> headers = new ArrayList<PemHeader>(2);
        headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
        headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));
        return new PemObject(type, headers, encData);
    }
    return new PemObject(type, encoding);
}
Also used : ArrayList(java.util.ArrayList) X509AttributeCertificate(org.bouncycastle.x509.X509AttributeCertificate) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DERInteger(org.bouncycastle.asn1.DERInteger) PemObjectGenerator(org.bouncycastle.util.io.pem.PemObjectGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) CRLException(java.security.cert.CRLException) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) X509AttributeCertificateHolder(org.bouncycastle.cert.X509AttributeCertificateHolder) CertificateEncodingException(java.security.cert.CertificateEncodingException) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) PemObject(org.bouncycastle.util.io.pem.PemObject) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) BigInteger(java.math.BigInteger) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) PemHeader(org.bouncycastle.util.io.pem.PemHeader)

Example 93 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project ovirt-engine by oVirt.

the class ExternalTrustStoreInitializer method addCertificate.

public static void addCertificate(Certificate cert) throws CertificateEncodingException, KeyStoreException {
    KeyStore keystore = getTrustStore();
    keystore.setCertificateEntry(Integer.toString(cert.hashCode()), cert);
    File trustStoreFile = EngineLocalConfig.getInstance().getExternalProvidersTrustStore();
    File tempFile = null;
    try {
        tempFile = File.createTempFile("keystore", ".tmp", trustStoreFile.getParentFile());
        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            keystore.store(out, EngineLocalConfig.getInstance().getExternalProvidersTrustStorePassword().toCharArray());
        }
        if (!tempFile.renameTo(trustStoreFile.getAbsoluteFile())) {
            throw new RuntimeException(String.format("Failed to save trust store to file %1$s", trustStoreFile.getAbsolutePath()));
        }
        tempFile = null;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (tempFile != null && !tempFile.delete()) {
            log.error("Cannot delete '{}'", tempFile.getAbsolutePath());
        }
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) KeyStore(java.security.KeyStore) File(java.io.File) KeyStoreException(java.security.KeyStoreException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 94 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project BiglyBT by BiglySoftware.

the class PrincipalUtil method getSubjectX509Principal.

/**
 * return the subject of the given cert as an X509PrincipalObject.
 */
public static X509Principal getSubjectX509Principal(X509Certificate cert) throws CertificateEncodingException {
    try {
        ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getTBSCertificate());
        ASN1InputStream aIn = new ASN1InputStream(bIn);
        TBSCertificateStructure tbsCert = new TBSCertificateStructure((ASN1Sequence) aIn.readObject());
        return new X509Principal(tbsCert.getSubject());
    } catch (IOException e) {
        throw new CertificateEncodingException(e.toString());
    }
}
Also used : ASN1InputStream(org.gudy.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) TBSCertificateStructure(org.gudy.bouncycastle.asn1.x509.TBSCertificateStructure) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException)

Example 95 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project xipki by xipki.

the class ScepImpl method buildSignedData.

// method pollCert
private SignedData buildSignedData(X509Certificate cert) throws OperationException {
    CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
    try {
        X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded());
        cmsSignedDataGen.addCertificate(certHolder);
        if (control.isIncludeCaCert()) {
            refreshCa();
            cmsSignedDataGen.addCertificate(caCert.getCertHolder());
        }
        CMSSignedData signedData = cmsSignedDataGen.generate(new CMSAbsentContent());
        return SignedData.getInstance(signedData.toASN1Structure().getContent());
    } catch (CMSException | IOException | CertificateEncodingException ex) {
        LogUtil.error(LOG, ex);
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
    }
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) CMSAbsentContent(org.bouncycastle.cms.CMSAbsentContent) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) OperationException(org.xipki.ca.api.OperationException) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

CertificateEncodingException (java.security.cert.CertificateEncodingException)210 X509Certificate (java.security.cert.X509Certificate)94 IOException (java.io.IOException)76 Certificate (java.security.cert.Certificate)29 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)27 KeyStoreException (java.security.KeyStoreException)19 MessageDigest (java.security.MessageDigest)19 ArrayList (java.util.ArrayList)19 X500Name (org.bouncycastle.asn1.x500.X500Name)16 CertificateException (java.security.cert.CertificateException)14 BigInteger (java.math.BigInteger)11 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)10 Bundle (android.os.Bundle)9 PublicKey (java.security.PublicKey)9 Date (java.util.Date)9 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 File (java.io.File)8 PrivateKey (java.security.PrivateKey)8 DEROctetString (org.bouncycastle.asn1.DEROctetString)8