List of usage examples for org.bouncycastle.asn1.x500.style RFC4519Style cn
ASN1ObjectIdentifier cn
To view the source code for org.bouncycastle.asn1.x500.style RFC4519Style cn.
Click Source Link
From source file:com.google.bitcoin.protocols.payments.PaymentSession.java
License:Apache License
/** * Uses the provided PKI method to find the corresponding public key and verify the provided signature. * Returns null if no PKI method was specified in the {@link Protos.PaymentRequest}. *///from www . j a v a 2 s . c o m public @Nullable PkiVerificationData verifyPki() throws PaymentRequestException { try { if (pkiVerificationData != null) return pkiVerificationData; if (paymentRequest.getPkiType().equals("none")) // Nothing to verify. Everything is fine. Move along. return null; String algorithm; if (paymentRequest.getPkiType().equals("x509+sha256")) algorithm = "SHA256withRSA"; else if (paymentRequest.getPkiType().equals("x509+sha1")) algorithm = "SHA1withRSA"; else throw new PaymentRequestException.InvalidPkiType( "Unsupported PKI type: " + paymentRequest.getPkiType()); Protos.X509Certificates protoCerts = Protos.X509Certificates.parseFrom(paymentRequest.getPkiData()); if (protoCerts.getCertificateCount() == 0) throw new PaymentRequestException.InvalidPkiData( "No certificates provided in message: server config error"); // Parse the certs and turn into a certificate chain object. Cert factories can parse both DER and base64. // The ordering of certificates is defined by the payment protocol spec to be the same as what the Java // crypto API requires - convenient! CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); List<X509Certificate> certs = Lists.newArrayList(); for (ByteString bytes : protoCerts.getCertificateList()) certs.add((X509Certificate) certificateFactory.generateCertificate(bytes.newInput())); CertPath path = certificateFactory.generateCertPath(certs); // Retrieves the most-trusted CAs from keystore. PKIXParameters params = new PKIXParameters(createKeyStore(trustStorePath)); // Revocation not supported in the current version. params.setRevocationEnabled(false); // Now verify the certificate chain is correct and trusted. This let's us get an identity linked pubkey. CertPathValidator validator = CertPathValidator.getInstance("PKIX"); PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(path, params); PublicKey publicKey = result.getPublicKey(); // OK, we got an identity, now check it was used to sign this message. Signature signature = Signature.getInstance(algorithm); // Note that we don't use signature.initVerify(certs.get(0)) here despite it being the most obvious // way to set it up, because we don't care about the constraints specified on the certificates: any // cert that links a key to a domain name or other identity will do for us. signature.initVerify(publicKey); Protos.PaymentRequest.Builder reqToCheck = paymentRequest.toBuilder(); reqToCheck.setSignature(ByteString.EMPTY); signature.update(reqToCheck.build().toByteArray()); if (!signature.verify(paymentRequest.getSignature().toByteArray())) throw new PaymentRequestException.PkiVerificationException( "Invalid signature, this payment request is not valid."); // Signature verifies, get the names from the identity we just verified for presentation to the user. final X509Certificate cert = certs.get(0); X500Principal principal = cert.getSubjectX500Principal(); // At this point the Java crypto API falls flat on its face and dies - there's no clean way to get the // different parts of the certificate name except for parsing the string. That's hard because of various // custom escaping rules and the usual crap. So, use Bouncy Castle to re-parse the string into binary form // again and then look for the names we want. Fail! org.bouncycastle.asn1.x500.X500Name name = new X500Name(principal.getName()); String entityName = null, orgName = null; for (RDN rdn : name.getRDNs()) { AttributeTypeAndValue pair = rdn.getFirst(); if (pair.getType().equals(RFC4519Style.cn)) entityName = ((ASN1String) pair.getValue()).getString(); else if (pair.getType().equals(RFC4519Style.o)) orgName = ((ASN1String) pair.getValue()).getString(); } if (entityName == null && orgName == null) { // This cert might not be an SSL cert. Just grab the first "subject alt name" if present, e.g. for // S/MIME certs. final Iterator<List<?>> it = cert.getSubjectAlternativeNames().iterator(); List<?> list; // email addresses have a type code of one. if (it.hasNext() && (list = it.next()) != null && (Integer) list.get(0) == 1) entityName = (String) list.get(1); if (entityName == null) throw new PaymentRequestException.PkiVerificationException( "Could not extract name from certificate"); } // Everything is peachy. Return some useful data to the caller. PkiVerificationData data = new PkiVerificationData(entityName, orgName, publicKey, result.getTrustAnchor()); // Cache the result so we don't have to re-verify if this method is called again. pkiVerificationData = data; return data; } catch (InvalidProtocolBufferException e) { // Data structures are malformed. throw new PaymentRequestException.InvalidPkiData(e); } catch (CertificateException e) { // The X.509 certificate data didn't parse correctly. throw new PaymentRequestException.PkiVerificationException(e); } catch (NoSuchAlgorithmException e) { // Should never happen so don't make users have to think about it. PKIX is always present. throw new RuntimeException(e); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException(e); } catch (CertPathValidatorException e) { // The certificate chain isn't known or trusted, probably, the server is using an SSL root we don't // know about and the user needs to upgrade to a new version of the software (or import a root cert). throw new PaymentRequestException.PkiVerificationException(e); } catch (InvalidKeyException e) { // Shouldn't happen if the certs verified correctly. throw new PaymentRequestException.PkiVerificationException(e); } catch (SignatureException e) { // Something went wrong during hashing (yes, despite the name, this does not mean the sig was invalid). throw new PaymentRequestException.PkiVerificationException(e); } catch (IOException e) { throw new PaymentRequestException.PkiVerificationException(e); } catch (KeyStoreException e) { throw new RuntimeException(e); } }
From source file:mitm.common.security.certificate.X500PrincipalBuilder.java
License:Open Source License
/** * Builds the X500Principal with the specified elements * //from w w w .j ava 2 s. c o m * Example DNs: * * CN=DOD CLASS 3 EMAIL CA-9, OU=PKI, OU=DoD, O=U.S. Government, C=US * CN=Thawte Personal Freemail Issuing CA, O=Thawte Consulting (Pty) Ltd., C=ZA * CN=Senter Certification Authority SubCA, OU=Certification Authority, O=Senter, L=Den Haag, ST=Zuid-Holland, * C=NL, EMAILADDRESS=SenterCA@Senter.nl * CN=Intel Corporation Basic Enterprise Issuing CA 1, OU=Information Technology Enterprise Business Computing, * O=Intel Corporation, L=Folsom, ST=CA, C=US, EMAILADDRESS=pki@intel.com * */ public X500Principal buildPrincipal() throws IOException { X500NameBuilder nameBuilder = new X500NameBuilder(RFC4519Style.INSTANCE); add(RFC4519Style.c, countryCode, nameBuilder); add(RFC4519Style.st, state, nameBuilder); add(RFC4519Style.l, locality, nameBuilder); add(RFC4519Style.o, organisation, nameBuilder); add(RFC4519Style.ou, organisationalUnit, nameBuilder); add(RFC4519Style.cn, commonName, nameBuilder); add(RFC4519Style.sn, surname, nameBuilder); add(RFC4519Style.givenName, givenName, nameBuilder); add(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, email, nameBuilder); return X500PrincipalUtils.fromX500Name(nameBuilder.build()); }
From source file:mitm.common.security.certificate.X500PrincipalInspector.java
License:Open Source License
/** * Returns a list of all common name elements from this principal. * All elements are returned so the list can contain duplicate elements * @return/*from ww w. j a v a 2 s. co m*/ */ public List<String> getCommonName() { return asStrings(RFC4519Style.cn); }
From source file:org.codice.ddf.security.certificate.generator.PkiTools.java
License:Open Source License
/** * Create an X500 name with a single populated attribute, the "common name". An X500 name object details the * identity of a machine, person, or organization. The name object is used as the "subject" of a certificate. * SSL/TLS typically uses a subject's common name as the DNS name for a machine and this name must be correct * or SSl/TLS will not trust the machine's certificate. * <p>/* w w w . ja va 2 s . co m*/ * TLS can use a different set of attributes to, the Subject Alternative Names. SANs are extensions to the * X509 specification and can include IP addresses, DNS names and other machine information. This package does * not use SANs. * * @param commonName the fully qualified host name of the end entity * @return X500 name object with common name attribute set * @see <a href="https://www.ietf.org/rfc/rfc4514.txt">RFC 4514, section 'LDAP: Distinguished Names'</a> * @see <a href="https://tools.ietf.org/html/rfc4519">RFC 4519 details the exact construction of distinguished names</a> * @see <a href="https://en.wikipedia.org/wiki/SubjectAltName">Subject Alternative Names on Wikipedia'</a> */ public static X500Name makeDistinguishedName(String commonName) { Validate.isTrue(commonName != null, "Certificate common name cannot be null"); assert commonName != null; if (commonName.isEmpty()) { LOGGER.warn( "Setting certificate common name to empty string. This could result in an unusable TLS certificate."); } X500NameBuilder nameBuilder = new X500NameBuilder(RFC4519Style.INSTANCE); //Add more nameBuilder.addRDN(....) statements to support more X500 attributes. nameBuilder.addRDN(RFC4519Style.cn, commonName); return nameBuilder.build(); }