/** * read in a BER encoded PKCS7 certificate. */ private Certificate readPKCS7Certificate( InputStream in) throws IOException { BERInputStream dIn = new BERInputStream(in); ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); if (seq.size() > 1 && seq.getObjectAt(0) instanceof DERObjectIdentifier) { if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) { sData = new SignedData(ASN1Sequence.getInstance( (ASN1TaggedObject)seq.getObjectAt(1), true)); return new X509CertificateObject( X509CertificateStructure.getInstance( sData.getCertificates().getObjectAt(sDataObjectCount++))); } } return new X509CertificateObject( X509CertificateStructure.getInstance(seq)); }
public void testTrustAndRemoteCertificatesWithDifferentEncodings() throws IOException, CertificateException, KeyStoreException, InvalidAlgorithmParameterException, CertPathValidatorException { X509CertPathImpl certPath = new X509CertPathImpl(Arrays.asList( new X509CertImpl(serviceSprintComCertChain[0]), new X509CertImpl(serviceSprintComCertChain[1]), new X509CertImpl(serviceSprintComCertChain[2]))); Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>(); trustAnchors.add(new TrustAnchor(new X509CertificateObject( new X509CertificateStructure( (ASN1Sequence) new ASN1InputStream(trustedCert).readObject())), null)); IndexedPKIXParameters indexedPKIXParameters = new IndexedPKIXParameters(trustAnchors); indexedPKIXParameters.setRevocationEnabled(false); new PKIXCertPathValidatorSpi().engineValidate(certPath, indexedPKIXParameters); // completing normally indicates that the certificate was valid }
private Certificate readDERCertificate( InputStream in) throws IOException { DERInputStream dIn = new DERInputStream(in); ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); if (seq.size() > 1 && seq.getObjectAt(0) instanceof DERObjectIdentifier) { if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) { sData = new SignedData(ASN1Sequence.getInstance( (ASN1TaggedObject)seq.getObjectAt(1), true)); return new X509CertificateObject( X509CertificateStructure.getInstance( sData.getCertificates().getObjectAt(sDataObjectCount++))); } } return new X509CertificateObject( X509CertificateStructure.getInstance(seq)); }
private void validateKeyUsage(X509CertificateStructure c, int keyUsageBits) throws IOException { X509Extensions exts = c.getTBSCertificate().getExtensions(); if (exts != null) { X509Extension ext = exts.getExtension(X509Extensions.KeyUsage); if (ext != null) { KeyUsage ku = KeyUsage.getInstance(ext); int bits = ku.getBytes()[0] & 0xff; if ((bits & keyUsageBits) != keyUsageBits) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown); } } } }
@SuppressWarnings({ "rawtypes", "resource" }) private DadesCertificat getDadesCertificat(X509Certificate cert) throws Exception { ASN1InputStream asn1is = new ASN1InputStream(cert.getEncoded()); org.bouncycastle.asn1.DERObject obj = asn1is.readObject(); /*byte[] value = cert.getExtensionValue(X509Extensions.BasicConstraints.toString()); BasicConstraints basicConstraints = new BasicConstraints(cert.getBasicConstraints()); if (basicConstraints.isCA()) return null;*/ DadesCertificat resposta = new DadesCertificat(); X509CertificateStructure certificate = new X509CertificateStructure((ASN1Sequence)obj); X509Name name = certificate.getSubject(); Vector oids = name.getOIDs(); Vector values = name.getValues(); for (int i = 0; i < oids.size(); i++) { if (oids.get(i).equals(X509Name.CN)) { processName(values.get(i).toString(), resposta); } else if (oids.get(i).equals(X509Name.SURNAME)) { resposta.setApellidosResponsable(values.get(i).toString()); } else if (oids.get(i).equals(X509Name.GIVENNAME)) { resposta.setNombreResponsable(values.get(i).toString()); } else if (oids.get(i).equals(X509Name.SN)) { resposta.setNifCif(values.get(i).toString()); resposta.setNifResponsable(values.get(i).toString()); } else if (oids.get(i).equals(OID_NIF_RESPONSABLE)) { resposta.setNifResponsable(values.get(i).toString()); } else if (oids.get(i).equals(X509Name.EmailAddress)) { resposta.setEmail(values.get(i).toString()); } else if (oids.get(i).equals(X509Name.C)) { //resposta.setPais(values.get(i).toString()); } else if (oids.get(i).equals(X509Name.O)) { resposta.setRazonSocial(values.get(i).toString()); } else if (oids.get(i).equals(X509Name.OU)) { //resposta.setDepartament(values.get(i).toString()); } else if (oids.get(i).equals(X509Name.T)) { //resposta.setCarrec(values.get(i).toString()); } } return resposta; }
public DatosCertificado(X509Certificate cert) throws Exception{ byte b[] = cert.getEncoded(); ASN1InputStream asn1is = new ASN1InputStream(b); org.bouncycastle.asn1.DERObject obj = asn1is.readObject(); X509CertificateStructure certificate = new X509CertificateStructure((ASN1Sequence)obj); X509Name name = certificate.getSubject(); personaFisica = false; personaJuridica = false; Vector v = name.getOIDs(); Vector value = name.getValues(); for(int i = 0; i < v.size(); i++) { if(v.get(i).equals(X509Name.CN)) processName(value.get(i).toString()); if(v.get(i).equals(X509Name.SURNAME)) surName = value.get(i).toString(); if(v.get(i).equals(X509Name.GIVENNAME)) givenName = value.get(i).toString(); if(v.get(i).equals(X509Name.CN)) processName(value.get(i).toString()); if(v.get(i).equals(X509Name.SN)) { nif = value.get(i).toString(); if(!personaJuridica) personaFisica = true; } if(v.get(i).equals(NIFOID)) { nifResponsable = v.get(i).toString(); personaFisica = false; personaJuridica = true; } } }
/** * @deprecated use constructor taking Certificate */ public IssuerAndSerialNumber( X509CertificateStructure certificate) { this.name = certificate.getIssuer(); this.serialNumber = certificate.getSerialNumber(); }
public static X509Extensions getExtensions(X509Certificate cert) throws Exception { ByteArrayInputStream bis = new ByteArrayInputStream(cert.getEncoded()); ASN1InputStream ais = new ASN1InputStream(bis); DERObject o = ais.readObject(); X509CertificateStructure struct = X509CertificateStructure .getInstance(o); return struct.getTBSCertificate().getExtensions(); }
/** * Parse the ServerCertificate message. * * @param is The stream where to parse from. * @return A Certificate object with the certs, the server has sended. * @throws IOException If something goes wrong during parsing. */ public static Certificate parse(InputStream is) throws IOException { X509CertificateStructure[] certs; int left = TlsUtils.readUint24(is); Vector tmp = new Vector(); while (left > 0) { int size = TlsUtils.readUint24(is); left -= 3 + size; byte[] buf = new byte[size]; TlsUtils.readFully(buf, is); ByteArrayInputStream bis = new ByteArrayInputStream(buf); ASN1InputStream ais = new ASN1InputStream(bis); ASN1Primitive o = ais.readObject(); tmp.addElement(X509CertificateStructure.getInstance(o)); if (bis.available() > 0) { throw new IllegalArgumentException( "Sorry, there is garbage data left after the certificate"); } } certs = new X509CertificateStructure[tmp.size()]; for (int i = 0; i < tmp.size(); i++) { certs[i] = (X509CertificateStructure)tmp.elementAt(i); } return new Certificate(certs); }
/** * @return An array which contains the certs, this chain contains. */ public X509CertificateStructure[] getCerts() { X509CertificateStructure[] result = new X509CertificateStructure[certs.length]; System.arraycopy(certs, 0, result, 0, certs.length); return result; }
public IssuerAndSerialNumber( X509CertificateStructure certificate) { this.name = certificate.getIssuer(); this.serialNumber = certificate.getSerialNumber(); }
/** * Generates a certificate object and initializes it with the data * read from the input stream inStream. */ public Certificate engineGenerateCertificate( InputStream in) throws CertificateException { if (sData != null && sDataObjectCount != sData.getCertificates().size()) { return new X509CertificateObject( X509CertificateStructure.getInstance( sData.getCertificates().getObjectAt(sDataObjectCount++))); } if (!in.markSupported()) { in = new BufferedInputStream(in); } try { in.mark(10); int tag = in.read(); if (tag == -1) { return null; } if (tag != 0x30) // assume ascii PEM encoded. { in.reset(); return readPEMCertificate(in); } else if (in.read() == 0x80) // assume BER encoded. { in.reset(); return readPKCS7Certificate(in); } else { in.reset(); return readDERCertificate(in); } } catch (IOException e) { throw new CertificateException(e.toString()); } }
public X509CertificateObject( X509CertificateStructure c) { this.c = c; }
private void testNullDerNullCert() throws Exception { KeyPair pair = generateLongFixedKeys(); PublicKey pubKey = pair.getPublic(); PrivateKey privKey = pair.getPrivate(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal("CN=Test")); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal("CN=Test")); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("MD5WithRSAEncryption"); X509Certificate cert = certGen.generate(privKey, "BC"); X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded())); ASN1Encodable tbsCertificate = struct.getTBSCertificate(); AlgorithmIdentifier sig = struct.getSignatureAlgorithm(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCertificate); v.add(new AlgorithmIdentifier(sig.getObjectId())); v.add(struct.getSignature()); // verify ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)fact.generateCertificate(bIn); cert.verify(cert.getPublicKey()); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e); } }
private void testNullDerNullCert() throws Exception { KeyPair pair = generateLongFixedKeys(); PublicKey pubKey = pair.getPublic(); PrivateKey privKey = pair.getPrivate(); ContentSigner sigGen = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(privKey); JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(new X500Name("CN=Test"),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),new X500Name("CN=Test"),pubKey); X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen)); X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded())); ASN1Encodable tbsCertificate = struct.getTBSCertificate(); AlgorithmIdentifier sig = struct.getSignatureAlgorithm(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCertificate); v.add(new AlgorithmIdentifier(sig.getAlgorithm())); v.add(struct.getSignature()); // verify ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509", BC); cert = (X509Certificate)fact.generateCertificate(bIn); cert.verify(cert.getPublicKey()); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e); } }
public void processServerCertificate(Certificate serverCertificate) throws IOException { X509CertificateStructure x509Cert = serverCertificate.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); try { this.serverPublicKey = PublicKeyFactory.createKey(keyInfo); } catch (RuntimeException e) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_unsupported_certificate); } // Sanity check the PublicKeyFactory if (this.serverPublicKey.isPrivate()) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_internal_error); } // TODO /* * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the * signing algorithm for the certificate must be the same as the algorithm for the * certificate key." */ // TODO Should the 'instanceof' tests be replaces with stricter checks on keyInfo.getAlgorithmId()? if (!(this.serverPublicKey instanceof RSAKeyParameters)) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown); } validateKeyUsage(x509Cert, KeyUsage.keyEncipherment); this.rsaServerPublicKey = validateRSAPublicKey((RSAKeyParameters)this.serverPublicKey); /* * Verify them. */ if (!this.verifyer.isValid(serverCertificate.getCerts())) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_user_canceled); } }
public void processServerCertificate(Certificate serverCertificate) throws IOException { X509CertificateStructure x509Cert = serverCertificate.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); try { this.serverPublicKey = PublicKeyFactory.createKey(keyInfo); } catch (RuntimeException e) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_unsupported_certificate); } // Sanity check the PublicKeyFactory if (this.serverPublicKey.isPrivate()) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_internal_error); } // TODO /* * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the * signing algorithm for the certificate must be the same as the algorithm for the * certificate key." */ // TODO Should the 'instanceof' tests be replaces with stricter checks on keyInfo.getAlgorithmId()? switch (this.keyExchange) { case TlsKeyExchange.KE_DH_DSS: if (!(this.serverPublicKey instanceof DHPublicKeyParameters)) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown); } // TODO The algorithm used to sign the certificate should be DSS. // x509Cert.getSignatureAlgorithm(); this.dhAgreeServerPublicKey = validateDHPublicKey((DHPublicKeyParameters)this.serverPublicKey); break; case TlsKeyExchange.KE_DH_RSA: if (!(this.serverPublicKey instanceof DHPublicKeyParameters)) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown); } // TODO The algorithm used to sign the certificate should be RSA. // x509Cert.getSignatureAlgorithm(); this.dhAgreeServerPublicKey = validateDHPublicKey((DHPublicKeyParameters)this.serverPublicKey); break; case TlsKeyExchange.KE_DHE_RSA: if (!(this.serverPublicKey instanceof RSAKeyParameters)) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown); } validateKeyUsage(x509Cert, KeyUsage.digitalSignature); break; case TlsKeyExchange.KE_DHE_DSS: if (!(this.serverPublicKey instanceof DSAPublicKeyParameters)) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown); } break; default: handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_unsupported_certificate); } /* * Verify them. */ if (!this.verifyer.isValid(serverCertificate.getCerts())) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_user_canceled); } }
public void processServerCertificate(Certificate serverCertificate) throws IOException { if (tlsSigner == null) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_unexpected_message); } X509CertificateStructure x509Cert = serverCertificate.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); try { this.serverPublicKey = PublicKeyFactory.createKey(keyInfo); } catch (RuntimeException e) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_unsupported_certificate); } // Sanity check the PublicKeyFactory if (this.serverPublicKey.isPrivate()) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_internal_error); } // TODO /* * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the * signing algorithm for the certificate must be the same as the algorithm for the * certificate key." */ switch (this.keyExchange) { case TlsKeyExchange.KE_SRP_RSA: if (!(this.serverPublicKey instanceof RSAKeyParameters)) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown); } validateKeyUsage(x509Cert, KeyUsage.digitalSignature); break; case TlsKeyExchange.KE_SRP_DSS: if (!(this.serverPublicKey instanceof DSAPublicKeyParameters)) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown); } break; default: handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_unsupported_certificate); } /* * Verify them. */ if (!this.verifyer.isValid(serverCertificate.getCerts())) { handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_user_canceled); } }
/** * Loads a X509 certificate from the specified input stream. * Input stream must contain DER-encoded certificate. * * @param in the input stream to read the certificate from. * @return <code>X509Certificate</code> the loaded certificate. * @exception GeneralSecurityException if certificate failed to load. */ public X509Certificate loadCertificate(InputStream in) throws IOException, GeneralSecurityException { DERInputStream derin = new DERInputStream(in); DERObject certInfo = derin.readObject(); ASN1Sequence seq = ASN1Sequence.getInstance(certInfo); return new X509CertificateObject(new X509CertificateStructure(seq)); }
/** * Loads a X509 certificate from the specified input stream. Input stream * must contain DER-encoded certificate. * * @param in * the input stream to read the certificate from. * @return <code>X509Certificate</code> the loaded certificate. * @exception GeneralSecurityException * if certificate failed to load. */ public X509Certificate loadCertificate(InputStream in) throws IOException, GeneralSecurityException { DERInputStream derin = new DERInputStream(in); DERObject certInfo = derin.readObject(); ASN1Sequence seq = ASN1Sequence.getInstance(certInfo); return new X509CertificateObject(new X509CertificateStructure(seq)); }