List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream
public ASN1InputStream(byte[] input)
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
License:Apache License
public UserDetails getUserFromCert(X509Certificate userCertificate) { String certDN = userCertificate.getSubjectDN().getName(); X500Name x500name = new X500Name(certDN); InetOrgPerson.Essence essence = new InetOrgPerson.Essence(); String name = getElement(x500name, BCStyle.CN); String uid = getElement(x500name, BCStyle.UID); essence.setUsername(uid);// w ww . j av a2 s . c o m essence.setUid(uid); essence.setDn(certDN); essence.setCn(new String[] { name }); essence.setSn(name); essence.setO(getElement(x500name, BCStyle.O)); essence.setOu(getElement(x500name, BCStyle.OU)); essence.setDescription(certDN); // Hack alert! There is no country property in this type, so we misuse PostalAddress... essence.setPostalAddress(getElement(x500name, BCStyle.C)); log.debug("Parsed certificate, name: " + name); // Extract info from Subject Alternative Name extension Collection<List<?>> san = null; try { san = userCertificate.getSubjectAlternativeNames(); } catch (CertificateParsingException e) { log.warn("could not extract info from Subject Alternative Names - will be ignored."); } // Check that the certificate includes the SubjectAltName extension if (san != null) { // Use the type OtherName to search for the certified server name Collection<GrantedAuthority> roles = new ArrayList<>(); for (List item : san) { Integer type = (Integer) item.get(0); if (type == 0) { // Type OtherName found so return the associated value ASN1InputStream decoder = null; String oid = ""; String value = ""; try { // Value is encoded using ASN.1 so decode it to get it out again decoder = new ASN1InputStream((byte[]) item.toArray()[1]); DLSequence seq = (DLSequence) decoder.readObject(); ASN1ObjectIdentifier asnOID = (ASN1ObjectIdentifier) seq.getObjectAt(0); ASN1Encodable encoded = seq.getObjectAt(1); encoded = ((DERTaggedObject) encoded).getObject(); encoded = ((DERTaggedObject) encoded).getObject(); oid = asnOID.getId(); value = ((DERUTF8String) encoded).getString(); } catch (UnsupportedEncodingException e) { log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e); continue; } catch (Exception e) { log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e); continue; } finally { if (decoder != null) { try { decoder.close(); } catch (IOException e) { } } } log.debug("oid: " + oid + ", value: " + value); switch (oid) { case MC_OID_FLAGSTATE: case MC_OID_CALLSIGN: case MC_OID_IMO_NUMBER: case MC_OID_MMSI_NUMBER: case MC_OID_AIS_SHIPTYPE: case MC_OID_PORT_OF_REGISTER: log.debug("Ship specific OIDs are ignored"); break; case MC_OID_MRN: // We only support 1 mrn essence.setUid(value); break; case MC_OID_PERMISSIONS: if (value != null && !value.trim().isEmpty()) { SimpleGrantedAuthority role = new SimpleGrantedAuthority(value); roles.add(role); } break; default: log.error("Unknown OID!"); break; } } else { // Other types are not supported so ignore them log.warn("SubjectAltName of invalid type found: " + type); } } if (!roles.isEmpty()) { essence.setAuthorities(roles); } } return essence.createUserDetails(); }
From source file:net.maritimecloud.pki.CertificateHandler.java
License:Apache License
/** * Extracts a PKIIdentity from a certificate using the MC PKI certificate "format" * * @param userCertificate The certificate * @return The extracted identity// www . ja va 2 s .c om */ public static PKIIdentity getIdentityFromCert(X509Certificate userCertificate) { PKIIdentity identity = new PKIIdentity(); String certDN = userCertificate.getSubjectDN().getName(); X500Name x500name = new X500Name(certDN); String name = getElement(x500name, BCStyle.CN); String uid = getElement(x500name, BCStyle.UID); identity.setMrn(uid); identity.setDn(certDN); identity.setCn(name); identity.setSn(name); identity.setO(getElement(x500name, BCStyle.O)); identity.setOu(getElement(x500name, BCStyle.OU)); identity.setCountry(getElement(x500name, BCStyle.C)); identity.setEmail(getElement(x500name, BCStyle.EmailAddress)); // Extract first and last name from full name String lastName = ""; String firstName = ""; if (name.split("\\w +\\w").length > 1) { lastName = name.substring(name.lastIndexOf(" ") + 1); firstName = name.substring(0, name.lastIndexOf(' ')); } else { firstName = name; } identity.setFirstName(firstName); identity.setLastName(lastName); log.debug("Parsed certificate, name: " + name); // Extract info from Subject Alternative Name extension Collection<List<?>> san = null; try { san = userCertificate.getSubjectAlternativeNames(); } catch (CertificateParsingException e) { log.warn("could not extract info from Subject Alternative Names - will be ignored."); } // Check that the certificate includes the SubjectAltName extension if (san != null) { // Use the type OtherName to search for the certified server name StringBuilder permissions = new StringBuilder(); for (List item : san) { Integer type = (Integer) item.get(0); if (type == 0) { // Type OtherName found so return the associated value ASN1InputStream decoder = null; String oid; String value; try { // Value is encoded using ASN.1 so decode it to get it out again decoder = new ASN1InputStream((byte[]) item.toArray()[1]); DLSequence seq = (DLSequence) decoder.readObject(); ASN1ObjectIdentifier asnOID = (ASN1ObjectIdentifier) seq.getObjectAt(0); ASN1Encodable encoded = seq.getObjectAt(1); oid = asnOID.getId(); // For some weird reason we need to do this 2 times - otherwise we get a // ClassCastException when extracting the value. encoded = ((DERTaggedObject) encoded).getObject(); encoded = ((DERTaggedObject) encoded).getObject(); value = ((DERUTF8String) encoded).getString(); } catch (UnsupportedEncodingException e) { log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e); continue; } catch (Exception e) { log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e); continue; } finally { if (decoder != null) { try { decoder.close(); } catch (IOException e) { e.printStackTrace(); } } } log.debug("oid: " + oid + ", value: " + value); switch (oid) { case MC_OID_FLAGSTATE: identity.setFlagState(value); break; case MC_OID_CALLSIGN: identity.setCallSign(value); break; case MC_OID_IMO_NUMBER: identity.setImoNumber(value); break; case MC_OID_MMSI_NUMBER: identity.setMmsiNumber(value); break; case MC_OID_AIS_SHIPTYPE: identity.setAisShipType(value); break; case MC_OID_PORT_OF_REGISTER: identity.setPortOfRegister(value); break; case MC_OID_MRN: // We only support 1 mrn identity.setMrn(value); break; case MC_OID_SHIP_MRN: identity.setShipMrn(value); case MC_OID_PERMISSIONS: if (value != null && !value.trim().isEmpty()) { if (permissions.length() == 0) { permissions = new StringBuilder(value); } else { permissions.append(',').append(value); } } break; default: log.error("Unknown OID!"); break; } } else { // Other types are not supported so ignore them log.warn("SubjectAltName of invalid type found: " + type); } } if (permissions.length() > 0) { identity.setPermissions(permissions.toString()); } } return identity; }
From source file:net.maritimecloud.pki.CRLVerifier.java
License:Apache License
/** * Extracts all CRL distribution point URLs from the * "CRL Distribution Point" extension in a X.509 certificate. If CRL * distribution point extension is unavailable, returns an empty list. *///from w w w .j a v a2 s. c o m public static List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateParsingException, IOException { byte[] crldpExt = cert.getExtensionValue(Extension.cRLDistributionPoints.getId()); if (crldpExt == null) { return new ArrayList<>(); } ASN1InputStream oAsnInStream = new ASN1InputStream(crldpExt); DEROctetString dosCrlDP = (DEROctetString) oAsnInStream.readObject(); byte[] crldpExtOctets = dosCrlDP.getOctets(); ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets)); CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(oAsnInStream2.readObject()); oAsnInStream.close(); oAsnInStream2.close(); List<String> crlUrls = new ArrayList<>(); for (DistributionPoint dp : crlDistPoint.getDistributionPoints()) { DistributionPointName dpn = dp.getDistributionPoint(); // Look for URIs in fullName if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) { GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames(); // Look for an URI for (GeneralName genName : genNames) { if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) { String url = DERIA5String.getInstance(genName.getName()).getString(); crlUrls.add(url); } } } } return crlUrls; }
From source file:net.ripe.rpki.commons.crypto.cms.RpkiSignedObjectParser.java
License:BSD License
private void parseContent(CMSSignedDataParser sp) { contentType = sp.getSignedContent().getContentType(); InputStream signedContentStream = sp.getSignedContent().getContentStream(); ASN1InputStream asn1InputStream = new ASN1InputStream(signedContentStream); try {// w w w . j a v a2s.c om decodeContent(asn1InputStream.readObject()); } catch (IOException e) { validationResult.rejectIfFalse(false, DECODE_CONTENT); return; } validationResult.rejectIfFalse(true, DECODE_CONTENT); try { validationResult.rejectIfFalse(asn1InputStream.readObject() == null, ONLY_ONE_SIGNED_OBJECT); asn1InputStream.close(); } catch (IOException e) { validationResult.rejectIfFalse(false, CMS_CONTENT_PARSING); } validationResult.rejectIfFalse(true, CMS_CONTENT_PARSING); }
From source file:net.ripe.rpki.commons.crypto.util.Asn1Util.java
License:BSD License
/** * Decodes the byte array extension using the {@link ASN1InputStream}. *//*from w ww . jav a2 s .com*/ public static ASN1Primitive decode(byte[] extension) { try { ASN1InputStream is = new ASN1InputStream(extension); return is.readObject(); } catch (IOException e) { throw new Asn1UtilException("IO exception while decoding resource extension", e); } }
From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectBuilderTest.java
License:BSD License
/** * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.2 *///from ww w.ja v a2 s .c o m @Test public void shouldCmsObjectHaveCorrectDigestAlgorithm() throws Exception { ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(cmsObject.getEncoded())); ContentInfo info = ContentInfo.getInstance(in.readObject()); SignedData signedData = SignedData.getInstance(info.getContent()); ASN1Set digestAlgorithms = signedData.getDigestAlgorithms(); ASN1Encodable asn1Object = digestAlgorithms.getObjectAt(0); AlgorithmIdentifier algorithmId = AlgorithmIdentifier.getInstance(asn1Object.toASN1Primitive()); assertEquals(DIGEST_SHA256, algorithmId.getAlgorithm().getId()); }
From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectParser.java
License:BSD License
private AlgorithmIdentifier getDigestAlgorithmOidFromEncodedCmsObject(byte[] data) { ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(data)); ContentInfo info;/*ww w.ja v a 2s .c om*/ try { info = ContentInfo.getInstance(in.readObject()); } catch (IOException e) { throw new ProvisioningCmsObjectParserException("error while reading cms object content info", e); } SignedData signedData = SignedData.getInstance(info.getContent()); ASN1Set digestAlgorithms = signedData.getDigestAlgorithms(); ASN1Encodable object = digestAlgorithms.getObjectAt(0); return AlgorithmIdentifier.getInstance(object.toASN1Primitive()); }
From source file:net.sabamiso.android.revocationtest.crl.RevocationTestUsingCRL.java
License:MIT License
private static CRLDistPoint getCRLDistPoint(byte[] asn1_bytes) { if (asn1_bytes == null) return null; CRLDistPoint crldp = null;//ww w . ja va 2s. c o m try { ASN1InputStream is1 = new ASN1InputStream(new ByteArrayInputStream(asn1_bytes)); ASN1Primitive p1 = is1.readObject(); if (p1 == null) return null; ASN1InputStream is2 = new ASN1InputStream(ASN1OctetString.getInstance(p1).getOctets()); ASN1Primitive p2 = is2.readObject(); if (p2 == null) return null; crldp = CRLDistPoint.getInstance(p2); } catch (IOException e) { e.printStackTrace(); } return crldp; }
From source file:net.sf.assinafacil.UtiICPBrasill.java
License:Open Source License
/** * Interpreta um dado do tipo otherName. * Obs. O JDK 5.0 no tem classes que lidem com um dado do tipo OtherName. * necessrio usar o BouncyCastle. /* w w w . j av a2 s . c om*/ * @param encoded O dado em ASN.1. * @return Um par contendo o OID e o contedo. */ private static Pair<DERObjectIdentifier, String> getOtherName(byte[] encoded) throws IOException { // O JDK 5.0 no tem classes que lidem com um dado do tipo OtherName. // necessrio usar o BouncyCastle. ASN1InputStream inps = new ASN1InputStream(encoded); DERSequence seq = null; DERObjectIdentifier oid = null; String conteudo = ""; seq = (DERSequence) inps.readObject(); inps.close(); Enumeration en = seq.getObjects(); oid = (DERObjectIdentifier) en.nextElement(); DERObject obj = ((ASN1TaggedObject) ((ASN1TaggedObject) en.nextElement()).getObject()).getObject(); if (obj instanceof DERString) { // Certificados antigos SERASA - incorretos conteudo = ((DERString) obj).getString(); } else if (obj instanceof DEROctetString) { // Certificados corretos conteudo = new String(((DEROctetString) obj).getOctets(), "ISO-8859-1"); } return new Pair<DERObjectIdentifier, String>(oid, conteudo); }
From source file:net.sf.assinafacil.UtiICPBrasill.java
License:Open Source License
public static Vector getCrlDistributionPoint(X509Certificate certificate) throws CertificateParsingException { try {//from w w w . ja va 2s . c o m // ---- alternative code ---------- byte[] val1 = certificate.getExtensionValue("2.5.29.31"); if (val1 == null) { return new Vector(); } ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1)); DERObject derObj = oAsnInStream.readObject(); DEROctetString dos = (DEROctetString) derObj; byte[] val2 = dos.getOctets(); ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2)); DERObject derObj2 = oAsnInStream2.readObject(); Vector urls = getDERValue(derObj2); return urls; } catch (Exception e) { e.printStackTrace(); throw new CertificateParsingException(e.toString()); } }