List of usage examples for org.bouncycastle.asn1 BERTags SEQUENCE
int SEQUENCE
To view the source code for org.bouncycastle.asn1 BERTags SEQUENCE.
Click Source Link
From source file:ca.trustpoint.m2m.M2mCertificateFactory.java
License:Apache License
/** * Generates a certificate object and initializes it with the data read from the * {@link java.io.InputStream InputStream} {@code inStream}. * * <p>//from w ww . j a v a2 s. c o m * The returned certificate object can be casted to the {@link M2mCertificate M2MCertificate} * class. * * <p> * The certificate provided in {@code inStream} must be DER-encoded and may be supplied in binary * or printable (Base64) encoding. If the certificate is provided in Base64 encoding, it must be * bounded at the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at the end by * -----END CERTIFICATE-----. * * <p> * Note that if the given input stream does not support {@link java.io.InputStream#mark(int) mark} * and {@link java.io.InputStream#reset() reset}, this method will consume the entire input * stream. Otherwise, each call to this method consumes one certificate and the read position of * the input stream is positioned to the next available byte after the inherent end-of-certificate * marker. If the data in the input stream does not contain an inherent end-of-certificate marker * (other than EOF) and there is trailing data after the certificate is parsed, a * {@link java.security.cert.CertificateException CertificateException} is thrown. * * @param inStream an input stream with the certificate data. * * @return a certificate object initialized with the data from the input stream. * * @exception CertificateException on parsing errors. */ @Override public Certificate engineGenerateCertificate(InputStream inStream) throws CertificateException { if (inStream == null) { throw new IllegalArgumentException("input stream is null"); } try { ASN1InputStream aIn = new ASN1InputStream(inStream); ASN1ApplicationSpecific app = ASN1ApplicationSpecific.getInstance(aIn.readObject()); aIn.close(); int appTag = app.getApplicationTag(); if (appTag != M2mCertificate.APPLICATION_TAG_NUMBER) { throw new IOException("not M2M certificate application tag: " + appTag); } ASN1Sequence seq = (ASN1Sequence) app.getObject(BERTags.SEQUENCE); if (seq.size() != 2) { throw new IOException("sequence wrong size for a M2M certificate"); } // Construct M2M certificate M2mCertificate cert = new M2mCertificate(); for (int i = 0; i < seq.size(); i++) { ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(i); CertificateFields tag = CertificateFields.getInstance(obj.getTagNo()); switch (tag) { case TBS_CERTIFICATE: ASN1Sequence tbsCertificate = ASN1Sequence.getInstance(obj, false); parseTbsCertificate(tbsCertificate, cert); break; case CA_CALC_VALUE: ASN1OctetString cACalcValue = ASN1OctetString.getInstance(obj, false); cert.setCaCalcValue(cACalcValue.getOctets()); break; default: throw new IOException("unknown M2M data field number: " + tag.getTagNumber()); } } return cert; } catch (Exception e) { // Catch all exceptions and convert it to a CertificateException throw new CertificateException("exception on parsing certificate data", e); } }
From source file:com.hierynomus.spnego.NegTokenInit.java
License:Apache License
private NegTokenInit read(Buffer<?> buffer) throws SpnegoException { try (ASN1InputStream is = new ASN1InputStream(buffer.asInputStream())) { ASN1Primitive applicationSpecific = is.readObject(); if (!(applicationSpecific instanceof BERApplicationSpecific || applicationSpecific instanceof DERApplicationSpecific)) { throw new SpnegoException( "Incorrect GSS-API ASN.1 token received, expected to find an [APPLICATION 0], not: " + applicationSpecific); }//from w w w .j ava2 s .c o m ASN1Sequence implicitSequence = (ASN1Sequence) ((ASN1ApplicationSpecific) applicationSpecific) .getObject(BERTags.SEQUENCE); ASN1Encodable spnegoOid = implicitSequence.getObjectAt(0); if (!(spnegoOid instanceof ASN1ObjectIdentifier)) { throw new SpnegoException("Expected to find the SPNEGO OID (" + SPNEGO + "), not: " + spnegoOid); } parseSpnegoToken(implicitSequence.getObjectAt(1)); } catch (IOException ioe) { throw new SpnegoException("Could not read NegTokenInit from buffer", ioe); } return this; }
From source file:de.tsenger.animamea.asn1.CVCertBody.java
License:Open Source License
public CVCertBody(DERApplicationSpecific derApp) throws IllegalArgumentException, IOException { if (derApp.getApplicationTag() != 0x4E) throw new IllegalArgumentException("contains no Certifcate Body with tag 0x7F4E"); else/*ww w.j a va2s . c om*/ cvcbody = derApp; ASN1Sequence bodySeq = (ASN1Sequence) cvcbody.getObject(BERTags.SEQUENCE); profileIdentifier = (ASN1Integer) ((DERApplicationSpecific) bodySeq.getObjectAt(0)) .getObject(BERTags.INTEGER); authorityReference = (DERIA5String) ((DERApplicationSpecific) bodySeq.getObjectAt(1)) .getObject(BERTags.IA5_STRING); ASN1Sequence pkSeq = (ASN1Sequence) ((DERApplicationSpecific) bodySeq.getObjectAt(2)) .getObject(BERTags.SEQUENCE); ASN1ObjectIdentifier pkOid = (ASN1ObjectIdentifier) pkSeq.getObjectAt(0); if (pkOid.toString().startsWith("0.4.0.127.0.7.2.2.2.2")) { publicKey = new AmECPublicKey(pkSeq); } else if (pkOid.toString().startsWith("0.4.0.127.0.7.2.2.2.1")) { publicKey = new AmRSAPublicKey(pkSeq); } chr = (DERIA5String) ((DERApplicationSpecific) bodySeq.getObjectAt(3)).getObject(BERTags.IA5_STRING); ASN1Sequence chatSeq = (ASN1Sequence) ((DERApplicationSpecific) bodySeq.getObjectAt(4)) .getObject(BERTags.SEQUENCE); chat = new CertificateHolderAuthorizationTemplate(chatSeq); effectiveDate = (DEROctetString) ((DERApplicationSpecific) bodySeq.getObjectAt(5)) .getObject(BERTags.OCTET_STRING); expirationDate = (DEROctetString) ((DERApplicationSpecific) bodySeq.getObjectAt(6)) .getObject(BERTags.OCTET_STRING); if (bodySeq.size() > 7) { extensions = (ASN1Sequence) ((DERApplicationSpecific) bodySeq.getObjectAt(7)) .getObject(BERTags.SEQUENCE); } }
From source file:de.tsenger.animamea.asn1.CVCertificate.java
License:Open Source License
public CVCertificate(byte[] in) throws IllegalArgumentException, IOException { ASN1StreamParser asn1Parser = new ASN1StreamParser(in); DERApplicationSpecific cvcert = (DERApplicationSpecific) asn1Parser.readObject(); if (cvcert.getApplicationTag() != 0x21) throw new IllegalArgumentException("Can't find a CV Certificate"); ASN1Sequence derCert = (ASN1Sequence) cvcert.getObject(BERTags.SEQUENCE); // Das CV Cerificate ist eine Sequence DERApplicationSpecific body = (DERApplicationSpecific) derCert.getObjectAt(0); //Das erste Objekt des Certificates ist der Cert-Body if (body.getApplicationTag() != 0x4E) throw new IllegalArgumentException("Can't find a Body in the CV Certificate"); certBody = new CVCertBody(body); DERApplicationSpecific signature = (DERApplicationSpecific) derCert.getObjectAt(1); //Das zweite Objekt des Certificates ist die Signatur if (signature.getApplicationTag() != 0x37) throw new IllegalArgumentException("Can't find a Signature in the CV Certificate"); certSignature = new CVCertSignature(signature.getContents()); }
From source file:de.tsenger.animamea.asn1.DynamicAuthenticationData.java
License:Open Source License
/** * Constructor for decoding/*from w w w . j ava2 s. co m*/ * @param data */ public DynamicAuthenticationData(byte[] data) { DERApplicationSpecific das = null; ASN1Sequence seq = null; try { das = (DERApplicationSpecific) DERApplicationSpecific.fromByteArray(data); seq = ASN1Sequence.getInstance(das.getObject(BERTags.SEQUENCE)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 0; i < seq.size(); i++) { DERTaggedObject temp = (DERTaggedObject) seq.getObjectAt(i); objects.add(temp); } }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
License:Open Source License
/** * Verify OCSP response for a malicious request. Uses nonsense payload. * * HTTP Content-length: 1000 byte ASN1 sequence length: 199995 byte Payload * size: 200000 byte (not including HTTP header) *///from ww w. j av a 2 s .co m @Test public void test18MaliciousOcspRequest() throws Exception { log.trace(">test18MaliciousOcspRequest"); int i = 0; // Construct the fake data. byte data[] = new byte[LimitLengthASN1Reader.MAX_REQUEST_SIZE * 2]; // The first byte indicate that this is a sequence. Necessary to past // the first test as an accepted OCSP object. data[0] = (byte) BERTags.SEQUENCE; // The second byte indicates the number if the following bytes are more // than can be represented by one byte and will be represented by 3 // bytes instead. data[1] = (byte) 0x83; // The third through the forth bytes are the number of the following // bytes. (0x030D3B = 199995) data[2] = (byte) 0x03; // MSB data[3] = (byte) 0x0D; data[4] = (byte) 0x3B; // LSB // Fill the rest of the array with some fake data. for (i = 5; i < data.length; i++) { data[i] = (byte) i; } // Create the HTTP header String path = "/ejbca/" + resourceOcsp; String headers = "POST " + path + " HTTP/1.1\r\n" + "Host: " + httpHost + "\r\n" + "Content-Type: application/ocsp-request\r\n" + "Content-Length: 1000\r\n" + "\r\n"; // Merge the HTTP headers and the raw data into one package. byte input[] = concatByteArrays(headers.getBytes(), data); // Create the socket. Socket socket = new Socket(InetAddress.getByName(httpHost), Integer.parseInt(httpPort)); OutputStream os = socket.getOutputStream(); try { // Send data byte for byte. try { os.write(input); } catch (IOException e) { log.info("Socket threw an IOException.", e); // Windows throws an IOException when trying to write more bytes to // the server than it should. JBoss on Linux does not. // assertTrue("Tried to write more than it should to the server (>1000), "+i, i > 1000); return; } /* Note that an Apache proxy interprets this as two requests in the same session (where the second one is bad): HTTP/1.1 200 OK Date: Thu, 27 Mar 2014 16:13:24 GMT Server: Apache/2.4.6 (Unix) OpenSSL/1.0.1e Content-Type: application/ocsp-response Content-Length: 5 0 HTTP/1.1 400 Bad Request Date: Thu, 27 Mar 2014 16:13:24 GMT Server: Apache/2.4.6 (Unix) OpenSSL/1.0.1e Content-Length: 226 Connection: close Content-Type: text/html; charset=iso-8859-1 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>400 Bad Request</title> </head><body> <h1>Bad Request</h1> <p>Your browser sent a request that this server could not understand.<br /> </p> </body></html> But since the response is ANS1 encoded, the response is still correctly parsed even though we provide 420 bytes extra. */ // Reading the response. InputStream ins = socket.getInputStream(); byte ret[] = new byte[1024]; int len = ins.read(ret); assertTrue("Could not read response.", len != -1); // Removing the HTTP headers. The HTTP headers end at the first occurrence of "\r\n\r\n". for (i = 3; i < len; i++) { if ((ret[i] == 0x0A) && (ret[i - 1] == 0x0D) && (ret[i - 2] == 0x0A) && (ret[i - 3] == 0x0D)) { break; } } log.info("response headers: " + new String(ret, 0, i)); int start = i + 1; byte respa[] = new byte[len - start]; for (i = start; i < len; i++) { respa[i - start] = ret[i]; } log.info("response contains: " + respa.length + " bytes."); log.info("response bytes: " + Hex.toHexString(respa)); log.info("response as string:" + new String(respa)); // Reading the response as a OCSPResp. When the input data array is // longer than allowed the OCSP response will return as an internal // error. OCSPResp response = new OCSPResp(respa); assertEquals("Incorrect response status.", OCSPRespBuilder.INTERNAL_ERROR, response.getStatus()); } finally { os.close(); socket.close(); } log.trace("<test18MaliciousOcspRequest"); }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
License:Open Source License
/** * Verify OCSP response for a malicious request. Uses nonsense payload. * * HTTP Content-length: 200000 byte ASN1 sequence length: 9996 byte Payload * size: 200000 byte (not including HTTP header) */// ww w . j a v a 2s.c om @Test public void test19MaliciousOcspRequest() throws Exception { log.trace(">test19MaliciousOcspRequest"); int i = 0; // Construct the fake data. byte data[] = new byte[LimitLengthASN1Reader.MAX_REQUEST_SIZE * 2]; // The first byte indicate that this is a sequence. Necessary to past // the first test as an accepted OCSP object. data[0] = (byte) BERTags.SEQUENCE; // The second byte indicates the number of the following bytes are more // than can be represented by one byte and will be represented by 2 // bytes instead. data[1] = (byte) 0x82; // The third through the forth bytes are the number of the following // bytes. (0x270C = 9996) data[2] = (byte) 0x27; // MSB data[3] = (byte) 0x0C; // LSB // Fill the rest of the array with some fake data. for (i = 4; i < data.length; i++) { data[i] = (byte) i; } // Create the HTTP header String path = "/ejbca/" + resourceOcsp; String headers = "POST " + path + " HTTP/1.1\r\n" + "Host: " + httpHost + "\r\n" + "Content-Type: application/ocsp-request\r\n" + "Content-Length: 200000\r\n" + "\r\n"; // Merge the HTTP headers and the raw data into one package. byte input[] = concatByteArrays(headers.getBytes(), data); // Create the socket. Socket socket = new Socket(InetAddress.getByName(httpHost), Integer.parseInt(httpPort)); // Send data byte for byte. OutputStream os = socket.getOutputStream(); try { os.write(input); } catch (IOException e) { log.info("Socket threw an IOException.", e); } // Reading the response. InputStream ins = socket.getInputStream(); byte ret[] = new byte[1024]; ins.read(ret); socket.close(); // Removing the HTTP headers. The HTTP headers end at the last // occurrence of "\r\n". for (i = ret.length - 1; i > 0; i--) { if ((ret[i] == 0x0A) && (ret[i - 1] == 0x0D)) { break; } } int start = i + 1; byte respa[] = new byte[ret.length - start]; for (i = start; i < ret.length; i++) { respa[i - start] = ret[i]; } log.info("response contains: " + respa.length + " bytes."); // Reading the response as a OCSPResp. OCSPResp response = new OCSPResp(respa); assertEquals("Incorrect response status.", OCSPRespBuilder.MALFORMED_REQUEST, response.getStatus()); log.trace("<test19MaliciousOcspRequest"); }
From source file:pro.javacard.gp.GlobalPlatform.java
License:Open Source License
private void parse_select_response(byte[] fci) throws GPException { try (ASN1InputStream ais = new ASN1InputStream(fci)) { if (ais.available() > 0) { // Read FCI DERApplicationSpecific fcidata = (DERApplicationSpecific) ais.readObject(); // FIXME System.out.println(ASN1Dump.dumpAsString(fcidata, true)); if (fcidata.getApplicationTag() == 15) { ASN1Sequence s = ASN1Sequence.getInstance(fcidata.getObject(BERTags.SEQUENCE)); for (ASN1Encodable e : Lists.newArrayList(s.iterator())) { ASN1TaggedObject t = DERTaggedObject.getInstance(e); if (t.getTagNo() == 4) { // ISD AID ASN1OctetString isdaid = DEROctetString.getInstance(t.getObject()); AID detectedAID = new AID(isdaid.getOctets()); if (sdAID == null) { logger.debug("Auto-detected ISD AID: " + detectedAID); }//from w ww .ja v a 2 s . c o m if (sdAID != null && !detectedAID.equals(sdAID)) { giveStrictWarning("SD AID in FCI does not match the requested AID!"); } this.sdAID = sdAID == null ? detectedAID : sdAID; } else if (t.getTagNo() == 5) { // Proprietary, usually a sequence if (t.getObject() instanceof ASN1Sequence) { ASN1Sequence prop = ASN1Sequence.getInstance(t.getObject()); for (ASN1Encodable enc : Lists.newArrayList(prop.iterator())) { ASN1Primitive proptag = enc.toASN1Primitive(); if (proptag instanceof DERApplicationSpecific) { DERApplicationSpecific isddata = (DERApplicationSpecific) proptag; if (isddata.getApplicationTag() == 19) { spec = GPData.get_version_from_card_data(isddata.getEncoded()); logger.debug("Auto-detected GP version: " + spec); } } else if (proptag instanceof DERTaggedObject) { DERTaggedObject tag = (DERTaggedObject) proptag; if (tag.getTagNo() == 101) { setBlockSize(DEROctetString.getInstance(tag.getObject())); } else if (tag.getTagNo() == 110) { logger.debug("Lifecycle data (ignored): " + HexUtils.bin2hex(tag.getObject().getEncoded())); } else { logger.info("Unknown/unhandled tag in FCI proprietary data: " + HexUtils.bin2hex(tag.getEncoded())); } } else { throw new GPException("Unknown data from card: " + HexUtils.bin2hex(proptag.getEncoded())); } } } else { // Except Feitian cards which have a plain nested tag if (t.getObject() instanceof DERTaggedObject) { DERTaggedObject tag = (DERTaggedObject) t.getObject(); if (tag.getTagNo() == 101) { setBlockSize(DEROctetString.getInstance(tag.getObject())); } else { logger.info("Unknown/unhandled tag in FCI proprietary data: " + HexUtils.bin2hex(tag.getEncoded())); } } } } else { logger.info("Unknown/unhandled tag in FCI: " + HexUtils.bin2hex(t.getEncoded())); } } } else { throw new GPException("Unknown data from card: " + HexUtils.bin2hex(fci)); } } } catch (IOException | ClassCastException e) { throw new GPException("Invalid data: " + e.getMessage(), e); } }
From source file:pro.javacard.gp.GPData.java
License:Open Source License
public static List<GPKeySet.GPKey> get_key_template_list(byte[] data) throws GPException { List<GPKey> r = new ArrayList<>(); try (ASN1InputStream ais = new ASN1InputStream(data)) { while (ais.available() > 0) { ASN1ApplicationSpecific keys = (DERApplicationSpecific) ais.readObject(); // System.out.println(ASN1Dump.dumpAsString(keys, true)); ASN1Sequence seq = (ASN1Sequence) keys.getObject(BERTags.SEQUENCE); for (ASN1Encodable p : Lists.newArrayList(seq.iterator())) { ASN1ApplicationSpecific key = (DERApplicationSpecific) p.toASN1Primitive(); byte[] tmpl = key.getContents(); if (tmpl.length < 4) { throw new GPDataException("Key info template shorter than 4 bytes", tmpl); }/*w w w. ja v a 2s .c o m*/ int id = tmpl[0] & 0xFF; int version = tmpl[1] & 0xFF; int type = tmpl[2] & 0xFF; int length = tmpl[3] & 0xFF; if (type == 0xFF) { throw new GPDataException("Extended key template not yet supported", tmpl); } r.add(new GPKey(version, id, length, type)); } } } catch (IOException | ClassCastException e) { throw new GPDataException("Could not parse key template: " + e.getMessage(), e); } return r; }
From source file:pro.javacard.gp.GPData.java
License:Open Source License
public static GPSpec get_version_from_card_data(byte[] data) throws GPException { try (ASN1InputStream ais = new ASN1InputStream(data)) { if (ais.available() > 0) { // Read card recognition data DERApplicationSpecific card_data = (DERApplicationSpecific) ais.readObject(); ASN1Sequence seq = (ASN1Sequence) card_data.getObject(BERTags.SEQUENCE); for (ASN1Encodable p : Lists.newArrayList(seq.iterator())) { if (p instanceof ASN1ObjectIdentifier) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) p; // Must be fixed if (!oid.toString().equalsIgnoreCase("1.2.840.114283.1")) { throw new GPDataException("Invalid CardRecognitionData: " + oid.toString()); }//from w ww . j a va 2 s . c o m } else if (p instanceof DERApplicationSpecific) { DERApplicationSpecific tag = (DERApplicationSpecific) p; int n = tag.getApplicationTag(); if (n == 0) { // Version String oid = ASN1ObjectIdentifier.getInstance(tag.getObject()).toString(); if (oid.equalsIgnoreCase("1.2.840.114283.2.2.1.1")) { return GPSpec.GP211; } else if (oid.equalsIgnoreCase("1.2.840.114283.2.2.2")) { return GPSpec.GP22; } else if (oid.equals("1.2.840.114283.2.2.2.1")) { return GPSpec.GP22; // TODO: no need to differentiate currently } else { throw new GPDataException("Invalid GP version OID: " + oid); } } } else { throw new GPDataException("Invalid type in card data", p.toASN1Primitive().getEncoded()); } } } } catch (IOException | ClassCastException e) { throw new GPDataException("Invalid data: " + e.getMessage()); } // Default to GP211 return GPSpec.GP211; }