List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject
public ASN1Primitive readObject() throws IOException
From source file:net.sf.keystore_explorer.crypto.x509.X509CertificateGenerator.java
License:Open Source License
private ASN1Encodable getExtensionValue(X509Extension extensions, String oid) throws CryptoException { ASN1InputStream ais = null; try {//ww w.ja v a 2s . c om ais = new ASN1InputStream(extensions.getExtensionValue(oid)); return ais.readObject(); } catch (IOException ex) { throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex); } finally { IOUtils.closeQuietly(ais); } }
From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java
License:Apache License
/** * Retrieves the list of alternative DNS names for this certificate, if any. * /*from w w w . jav a 2 s .c om*/ * @param cert * The certificate from which the issuer name is to the * extracted. * @return A list with all alternative DNS names included in the * certificate. * @throws IOException */ public static List extractSubjectAlternativeNameList(org.bouncycastle.asn1.x509.Certificate cert) throws IOException { List dnsNames = new ArrayList(); dnsNames.add(CertificateValidatorUtils.extractCommonName(cert, true)); Extension subjectAlternativeName = cert.getTBSCertificate().getExtensions() .getExtension(Extension.subjectAlternativeName); if (subjectAlternativeName == null) { return dnsNames; } ASN1OctetString oct = subjectAlternativeName.getExtnValue(); ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())); GeneralNames gn = GeneralNames.getInstance(extIn.readObject()); extIn.close(); ASN1Sequence sq = (ASN1Sequence) gn.toASN1Primitive(); for (int i = 0; i != sq.size(); i++) { GeneralName n = GeneralName.getInstance(sq.getObjectAt(i)); dnsNames.add(n.getName().toString()); } return dnsNames; }
From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java
License:Apache License
private static Boolean isHostAunthenticationCertificate(Certificate cert) throws IOException { Extension extKeyUsageExtension = cert.getTBSCertificate().getExtensions() .getExtension(Extension.extendedKeyUsage); if (extKeyUsageExtension == null) { return Boolean.FALSE; }//from w ww. j ava2 s .c o m ASN1OctetString oct = extKeyUsageExtension.getExtnValue(); ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())); ExtendedKeyUsage extKeyUsages = ExtendedKeyUsage.getInstance(extIn.readObject()); extIn.close(); KeyPurposeId[] keyPurposeIds = extKeyUsages.getUsages(); for (int i = 0; i < keyPurposeIds.length; i++) { if (keyPurposeIds[i].equals(KeyPurposeId.id_kp_serverAuth)) { return Boolean.TRUE; } } return Boolean.FALSE; }
From source file:nl.uva.vlet.grid.voms.VomsProxyCredential.java
License:Apache License
/** * Contacts the VOMS server to get an AttributeCertificate * /*w w w . j a v a 2 s.c om*/ * @return true if successful, false if not * @throws GSSException * @throws IOException */ private boolean createAC() throws Exception { String hostid = vo.getDefaultHost() + ":" + vo.getDefaultPort(); infoPrintf("Contacting VOMS server [" + hostid + "] for vo:" + vo.getVoName() + "\n"); // System.out.println("Contacting VOMS server [" + vo.getHost() + " on // port "+ vo.getPort()+ " ]..."); GSSManager manager = new GlobusGSSManagerImpl(); Authorization authorization = new IdentityAuthorization(vo.getDefaultHostDN()); GSSCredential clientCreds = (GSSCredential) new GlobusGSSCredentialImpl(plainProxy, GSSCredential.INITIATE_ONLY); ExtendedGSSContext context = (ExtendedGSSContext) manager.createContext(null, GSSConstants.MECH_OID, clientCreds, GSSContext.DEFAULT_LIFETIME); context.requestMutualAuth(true); context.requestCredDeleg(false); context.requestConf(true); context.requestAnonymity(false); context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_GSI); context.setOption(GSSConstants.REJECT_LIMITED_PROXY, new Boolean(false)); GssSocket socket = null; OutputStream out = null; InputStream in = null; // // P.T. de Boer: // Nest exception and add usefull information to exception: // try { socket = (GssSocket) GssSocketFactory.getDefault().createSocket(vo.getDefaultHost(), vo.getDefaultPort(), context); socket.setWrapMode(GssSocket.GSI_MODE); socket.setAuthorization(authorization); out = ((Socket) socket).getOutputStream(); in = ((Socket) socket).getInputStream(); } // // NoRoute= wrong port and/or hostname catch (java.net.NoRouteToHostException e) { // Wrap as nested VL Exception and provide better // information: throw new VlIOException( "Communication Error. Adres or port is wrong or server is not reachable:" + hostid, e); } catch (java.net.ConnectException e) { // Wrap as nested VL Exception and provide better // information: throw new VlIOException("Connection Error. Adres or port is wrong or server is not reachable:" + hostid, e); } catch (java.net.SocketException e) { // Generic Socket Exception. // Wrap as nested VL Exception and provide better // information: // when authentication fails, the socket is closed also. throw new VlIOException( "Communication Error. Either SSL authentication failed or the adres or port is wrong (server not reachable):" + hostid, e); } /* * if (socket.isConnected()==false) { throw new IOException("Socket not * connected:"+socket.getInetAddress()+":"+socket.getPort()); } */ if (in == null) { // VlException throw new VlIOException( "Couldn't read from socket:" + socket.getInetAddress() + ":" + socket.getPort()); } String msg = new String("<?xml version=\"1.0\" encoding = \"US-ASCII\"?>" + "<voms>" + "<command>" + command + "</command>" + "<lifetime>" + lifetimeInSeconds + "</lifetime>" + "</voms>"); debugPrintf("Sending message to:%s\n--- START ---\n%s\n--- END ---\n", hostid, msg); byte[] outToken = msg.getBytes(); out.write(outToken); out.flush(); StringBuffer voms_server_answer = new StringBuffer(); BufferedReader buff = new BufferedReader(new InputStreamReader(in)); char[] buf = new char[1024]; int numRead = 0; // // read loop: // do { numRead = buff.read(buf); if (numRead > 0) { voms_server_answer.append(buf, 0, numRead); } } while (numRead >= 0); // while not EOF if (voms_server_answer.length() <= 0) { errorPrintf("empty or null voms_server_answer\n"); // P.T. de Boer: Do error checking ! throw new VlIOException("NULL reply from socket (command=" + command + "):" + socket.getInetAddress() + ":" + socket.getPort()); } // String answer = buff.readLine(); out.close(); in.close(); buff.close(); String answer = voms_server_answer.toString(); if (answer.indexOf("<error>") > 0) { String errormsg = answer.substring(answer.indexOf("<message>") + 9, answer.indexOf("</message>")); infoPrintf("Received error message from server:%s\n", errormsg); // P.T. de Boer: // This is NOT a warning: myLogger.warn("VOMS server returned an // error => " + errormsg); // throw error: throw new VlServerException("Error when communicating with:" + hostid + ".\nError=" + errormsg); } String encoded; try { encoded = answer.substring(answer.indexOf("<ac>") + 4, answer.indexOf("</ac>")); } catch (IndexOutOfBoundsException e) { // P.T. de Boer. This is an error as well: Nest Exception: throw new VlServerException("Message Error. Could not find encoded voms proxy in server answer.", e); } // System.out.println(" succes " + encoded); try { byte[] payload = VincenzoBase64.decode(encoded); // byte[] payload = Base64Coder.decode(encoded); //Debug(4,"Payload="(new String(payload)) ByteArrayInputStream is = new ByteArrayInputStream(payload); ASN1InputStream asnInStream = new ASN1InputStream(is); // org.bouncycastle.asn1.BERTaggedObjectParser btp = // (org.bouncycastle.asn1.BERTaggedObjectParser)asnInStream.readObject(); ASN1Sequence acseq = (ASN1Sequence) asnInStream.readObject(); ac = new AttributeCertificate(acseq); return true; } catch (Exception e) { // P.T. de Boer nested VlException throw new VlException("DecodingError", "Couldn't decode server answer\n" + encoded, e); } }
From source file:org.apache.catalina.realm.X509SubjectAlternativeNameRetriever.java
License:Apache License
/** * The method converts ASNDerEncodedByteArray into String * @param byteArray//w ww . j ava2 s. c om * @return String */ private String getStringFromASNDerEncodedByteArray(byte[] byteArray) { if (logger.isDebugEnabled()) { logger.debug("getStringFromASNDerEncodedByteArray(byte[]) - start"); } String ret = null; try { ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(byteArray)); DERObject derObject = asn1InputStream.readObject(); ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(derObject); Object objectValue = asn1Sequence.getObjectAt(1); if (objectValue instanceof ASN1TaggedObject) { ASN1TaggedObject asn1TaggedObject = (ASN1TaggedObject) objectValue; try { if (logger.isDebugEnabled()) { logger.debug("Try to get string from DERUTF8String."); } DERObject derTaggedObject = asn1TaggedObject.getObject(); DERUTF8String derUtf8String = DERUTF8String.getInstance(derTaggedObject); ret = derUtf8String.getString(); } catch (IllegalArgumentException e) { if (logger.isDebugEnabled()) { logger.debug("Can not get String From DERUTF8String, [" + e.getMessage() + "]."); } } } } catch (Exception e) { if (logger.isInfoEnabled()) { logger.info("Can not get String From ASNDerEncoded ByteArray, [" + e.getMessage() + "]."); } } if (logger.isDebugEnabled()) { logger.debug("getStringFromASNDerEncodedByteArray(byte[]) - end. Ret is [" + ret + "]."); } return ret; }
From source file:org.apache.cxf.ws.security.sts.provider.cert.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. *//* ww w. j a v a 2s. co m*/ public static List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateParsingException, IOException { byte[] crldpExt = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId()); if (crldpExt == null) { List<String> emptyList = new ArrayList<String>(); return emptyList; } ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(crldpExt)); DERObject derObjCrlDP = oAsnInStream.readObject(); DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP; byte[] crldpExtOctets = dosCrlDP.getOctets(); ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets)); DERObject derObj2 = oAsnInStream2.readObject(); CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2); List<String> crlUrls = new ArrayList<String>(); for (DistributionPoint dp : distPoint.getDistributionPoints()) { DistributionPointName dpn = dp.getDistributionPoint(); // Look for URIs in fullName if (dpn != null) { if (dpn.getType() == DistributionPointName.FULL_NAME) { GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames(); // Look for an URI for (int j = 0; j < genNames.length; j++) { if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) { String url = DERIA5String.getInstance(genNames[j].getName()).getString(); crlUrls.add(url); } } } } } return crlUrls; }
From source file:org.apache.http.contrib.auth.BouncySpnegoTokenGenerator.java
License:Apache License
public byte[] generateSpnegoDERObject(byte[] kerbTicket) throws IOException { DEROctetString ourKerberosTicket = new DEROctetString(kerbTicket); DERSequence kerbOidSeq = new DERSequence(kerbOid); DERTaggedObject tagged0 = new DERTaggedObject(0, kerbOidSeq); DERTaggedObject tagged2 = new DERTaggedObject(2, ourKerberosTicket); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tagged0);// w ww.ja va2s . c o m v.add(tagged2); DERSequence seq = new DERSequence(v); DERTaggedObject taggedSpnego = new DERTaggedObject(0, seq); ByteArrayOutputStream out = new ByteArrayOutputStream(); ASN1OutputStream asn1Out = new ASN1OutputStream(out); ASN1Object spnegoOIDASN1 = (ASN1Object) spnegoOid.toASN1Object(); ASN1Object taggedSpnegoASN1 = (ASN1Object) taggedSpnego.toASN1Object(); int length = spnegoOIDASN1.getDEREncoded().length + taggedSpnegoASN1.getDEREncoded().length; byte[] lenBytes = writeLength(length); byte[] appWrap = new byte[lenBytes.length + 1]; appWrap[0] = 0x60; for (int i = 1; i < appWrap.length; i++) { appWrap[i] = lenBytes[i - 1]; } asn1Out.write(appWrap); asn1Out.writeObject(spnegoOid.toASN1Object()); asn1Out.writeObject(taggedSpnego.toASN1Object()); byte[] app = out.toByteArray(); ASN1InputStream in = new ASN1InputStream(app); if (log.isDebugEnabled()) { int skip = 12; byte[] manipBytes = new byte[app.length - skip]; for (int i = skip; i < app.length; i++) { manipBytes[i - skip] = app[i]; } ASN1InputStream ourSpnego = new ASN1InputStream(manipBytes); log.debug(ASN1Dump.dumpAsString(ourSpnego.readObject())); } return in.readObject().getDEREncoded(); }
From source file:org.apache.pdfbox.pdmodel.encryption.PublicKeySecurityHandler.java
License:Apache License
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws GeneralSecurityException, IOException { ASN1InputStream asn1inputstream = new ASN1InputStream( new ByteArrayInputStream(x509certificate.getTBSCertificate())); TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure .getInstance(asn1inputstream.readObject()); AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo() .getAlgorithmId();// ww w . j a va2s.c o m IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(), tbscertificatestructure.getSerialNumber().getValue()); Cipher cipher = Cipher.getInstance(algorithmidentifier.getObjectId().getId()); cipher.init(1, x509certificate.getPublicKey()); DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0)); RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber); return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring); }
From source file:org.apache.poi.poifs.crypt.dsig.facets.XAdESXLSignatureFacet.java
License:Apache License
private BigInteger getCrlNumber(X509CRL crl) { try {//from w w w . j a v a 2 s . co m byte[] crlNumberExtensionValue = crl.getExtensionValue(Extension.cRLNumber.getId()); if (null == crlNumberExtensionValue) { return null; } @SuppressWarnings("resource") ASN1InputStream asn1InputStream = new ASN1InputStream(crlNumberExtensionValue); ASN1OctetString octetString = (ASN1OctetString) asn1InputStream.readObject(); byte[] octets = octetString.getOctets(); asn1InputStream = new ASN1InputStream(octets); ASN1Integer integer = (ASN1Integer) asn1InputStream.readObject(); BigInteger crlNumber = integer.getPositiveValue(); return crlNumber; } catch (Exception e) { throw new RuntimeException("I/O error: " + e.getMessage(), e); } }
From source file:org.apache.synapse.transport.certificatevalidation.crl.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./* ww w . ja v a2 s. c o m*/ */ private List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateVerificationException { //Gets the DER-encoded OCTET string for the extension value for CRLDistributionPoints byte[] crlDPExtensionValue = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId()); if (crlDPExtensionValue == null) throw new CertificateVerificationException("Certificate doesn't have CRL Distribution points"); //crlDPExtensionValue is encoded in ASN.1 format. ASN1InputStream asn1In = new ASN1InputStream(crlDPExtensionValue); //DER (Distinguished Encoding Rules) is one of ASN.1 encoding rules defined in ITU-T X.690, 2002, specification. //ASN.1 encoding rules can be used to encode any data object into a binary file. Read the object in octets. CRLDistPoint distPoint; try { DEROctetString crlDEROctetString = (DEROctetString) asn1In.readObject(); //Get Input stream in octets ASN1InputStream asn1InOctets = new ASN1InputStream(crlDEROctetString.getOctets()); DERObject crlDERObject = asn1InOctets.readObject(); distPoint = CRLDistPoint.getInstance(crlDERObject); } catch (IOException e) { throw new CertificateVerificationException("Cannot read certificate to get CRL urls", e); } List<String> crlUrls = new ArrayList<String>(); //Loop through ASN1Encodable DistributionPoints for (DistributionPoint dp : distPoint.getDistributionPoints()) { //get ASN1Encodable DistributionPointName DistributionPointName dpn = dp.getDistributionPoint(); if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) { //Create ASN1Encodable General Names GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames(); // Look for a URI //todo: May be able to check for OCSP url specifically. for (GeneralName genName : genNames) { if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) { //DERIA5String contains an ascii string. //A IA5String is a restricted character string type in the ASN.1 notation String url = DERIA5String.getInstance(genName.getName()).getString().trim(); crlUrls.add(url); } } } } if (crlUrls.isEmpty()) throw new CertificateVerificationException("Cant get CRL urls from certificate"); return crlUrls; }