List of usage examples for java.io DataInputStream read
public int read() throws IOException
From source file:org.opensc.pkcs15.token.impl.CardOSToken.java
@Override public MF selectMF() throws IOException { // SELECT FILE, P1=0x00, P2=0x00, no data -> select MF CommandAPDU cmd = new CommandAPDU(0x00, 0xA4, 0x00, 0x00, DEFAULT_LE); try {//from w w w . j a v a 2 s.com ResponseAPDU resp = this.channel.transmit(cmd); DataInputStream dis = getSelectFileData(resp); long bodySize = 0; int acLifeCycle = TokenFileAcl.AC_ALWAYS; int acUpdate = TokenFileAcl.AC_ALWAYS; int acAppend = TokenFileAcl.AC_ALWAYS; int acDeactivate = TokenFileAcl.AC_ALWAYS; int acActivate = TokenFileAcl.AC_ALWAYS; int acDelete = TokenFileAcl.AC_ALWAYS; int acAdmin = TokenFileAcl.AC_ALWAYS; int acCreate = TokenFileAcl.AC_ALWAYS; int acExecute = TokenFileAcl.AC_ALWAYS; int acAllocate = TokenFileAcl.AC_ALWAYS; int tag; while ((tag = dis.read()) >= 0) { int n = dis.read(); if (n < 0) break; switch (tag) { case 0x81: if (n != 2) throw new IOException("Invalid length [" + n + "] of FCI tag 0x81."); bodySize = dis.readUnsignedShort(); break; case 0x83: if (n != 2) throw new IOException("Invalid length [" + n + "] of FCI tag 0x83."); int tpath = dis.readUnsignedShort(); if (tpath != PathHelper.MF_ID) throw new IOException("File ID [" + PathHelper.formatID(tpath) + "] reported by SELECT FILE differs from requested ID [" + PathHelper.formatID(PathHelper.MF_ID) + "]."); break; case 0x86: if (n >= 1) acLifeCycle = dis.read(); if (n >= 2) acUpdate = dis.read(); if (n >= 3) acAppend = dis.read(); if (n >= 4) acDeactivate = dis.read(); if (n >= 5) acActivate = dis.read(); if (n >= 6) acDelete = dis.read(); if (n >= 7) acAdmin = dis.read(); if (n >= 8) acCreate = dis.read(); if (n >= 9) acExecute = dis.read(); if (n >= 10) acAllocate = dis.read(); if (n != 10) log.warn("Invalid length [" + n + "] of FCI tag 0x86 for MF."); if (n > 10) dis.skipBytes(n - 10); break; default: byte[] tmp = new byte[n]; dis.readFully(tmp); log.warn("skipping FCI tag [0x" + Integer.toHexString(tag) + "], data [" + Util.asHex(tmp) + "]."); } } MF mf = new MF(PathHelper.MF_PATH, bodySize, acLifeCycle, acUpdate, acAppend, acDeactivate, acActivate, acDelete, acAdmin, acCreate, acExecute, acAllocate); this.currentFile = mf; return mf; } catch (CardException e) { throw new PKCS15Exception("Error sending select MF", e); } }
From source file:su.comp.bk.ui.BkEmuActivity.java
/** * Load image in bin format (address/length/data) from byte array. * @param imageData image data byte array * @throws IOException in case of loading error *//*from ww w . j a v a 2 s .c om*/ public int loadBinImage(byte[] imageData) throws IOException { if (imageData.length < 5 || imageData.length > 01000000) { throw new IllegalArgumentException("Invalid binary image file length: " + imageData.length); } DataInputStream imageDataInputStream = new DataInputStream( new ByteArrayInputStream(imageData, 0, imageData.length)); lastBinImageAddress = (imageDataInputStream.readByte() & 0377) | ((imageDataInputStream.readByte() & 0377) << 8); lastBinImageLength = (imageDataInputStream.readByte() & 0377) | ((imageDataInputStream.readByte() & 0377) << 8); synchronized (computer) { for (int imageIndex = 0; imageIndex < lastBinImageLength; imageIndex++) { if (!computer.writeMemory(true, lastBinImageAddress + imageIndex, imageDataInputStream.read())) { throw new IllegalStateException("Can't write binary image data to address: 0" + Integer.toOctalString(lastBinImageAddress) + imageIndex); } } } Log.d(TAG, "loaded bin image file: address 0" + Integer.toOctalString(lastBinImageAddress) + ", length: " + lastBinImageLength); return lastBinImageAddress; }
From source file:org.apache.hadoop.crypto.TestCryptoCodec.java
private void cryptoCodecTest(Configuration conf, int seed, int count, String encCodecClass, String decCodecClass, byte[] iv) throws IOException, GeneralSecurityException { CryptoCodec encCodec = null;/*from w w w . j a va 2 s. c o m*/ try { encCodec = (CryptoCodec) ReflectionUtils.newInstance(conf.getClassByName(encCodecClass), conf); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto codec!"); } LOG.info("Created a Codec object of type: " + encCodecClass); // Generate data DataOutputBuffer data = new DataOutputBuffer(); RandomDatum.Generator generator = new RandomDatum.Generator(seed); for (int i = 0; i < count; ++i) { generator.next(); RandomDatum key = generator.getKey(); RandomDatum value = generator.getValue(); key.write(data); value.write(data); } LOG.info("Generated " + count + " records"); // Encrypt data DataOutputBuffer encryptedDataBuffer = new DataOutputBuffer(); CryptoOutputStream out = new CryptoOutputStream(encryptedDataBuffer, encCodec, bufferSize, key, iv); out.write(data.getData(), 0, data.getLength()); out.flush(); out.close(); LOG.info("Finished encrypting data"); CryptoCodec decCodec = null; try { decCodec = (CryptoCodec) ReflectionUtils.newInstance(conf.getClassByName(decCodecClass), conf); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto codec!"); } LOG.info("Created a Codec object of type: " + decCodecClass); // Decrypt data DataInputBuffer decryptedDataBuffer = new DataInputBuffer(); decryptedDataBuffer.reset(encryptedDataBuffer.getData(), 0, encryptedDataBuffer.getLength()); CryptoInputStream in = new CryptoInputStream(decryptedDataBuffer, decCodec, bufferSize, key, iv); DataInputStream dataIn = new DataInputStream(new BufferedInputStream(in)); // Check DataInputBuffer originalData = new DataInputBuffer(); originalData.reset(data.getData(), 0, data.getLength()); DataInputStream originalIn = new DataInputStream(new BufferedInputStream(originalData)); for (int i = 0; i < count; ++i) { RandomDatum k1 = new RandomDatum(); RandomDatum v1 = new RandomDatum(); k1.readFields(originalIn); v1.readFields(originalIn); RandomDatum k2 = new RandomDatum(); RandomDatum v2 = new RandomDatum(); k2.readFields(dataIn); v2.readFields(dataIn); assertTrue("original and encrypted-then-decrypted-output not equal", k1.equals(k2) && v1.equals(v2)); // original and encrypted-then-decrypted-output have the same hashCode Map<RandomDatum, String> m = new HashMap<RandomDatum, String>(); m.put(k1, k1.toString()); m.put(v1, v1.toString()); String result = m.get(k2); assertEquals("k1 and k2 hashcode not equal", result, k1.toString()); result = m.get(v2); assertEquals("v1 and v2 hashcode not equal", result, v1.toString()); } // Decrypt data byte-at-a-time originalData.reset(data.getData(), 0, data.getLength()); decryptedDataBuffer.reset(encryptedDataBuffer.getData(), 0, encryptedDataBuffer.getLength()); in = new CryptoInputStream(decryptedDataBuffer, decCodec, bufferSize, key, iv); // Check originalIn = new DataInputStream(new BufferedInputStream(originalData)); int expected; do { expected = originalIn.read(); assertEquals("Decrypted stream read by byte does not match", expected, in.read()); } while (expected != -1); // Seek to a certain position and decrypt originalData.reset(data.getData(), 0, data.getLength()); decryptedDataBuffer.reset(encryptedDataBuffer.getData(), 0, encryptedDataBuffer.getLength()); in = new CryptoInputStream(new TestCryptoStreams.FakeInputStream(decryptedDataBuffer), decCodec, bufferSize, key, iv); int seekPos = data.getLength() / 3; in.seek(seekPos); // Check TestCryptoStreams.FakeInputStream originalInput = new TestCryptoStreams.FakeInputStream(originalData); originalInput.seek(seekPos); do { expected = originalInput.read(); assertEquals("Decrypted stream read by byte does not match", expected, in.read()); } while (expected != -1); LOG.info("SUCCESS! Completed checking " + count + " records"); // Check secure random generator testSecureRandom(encCodec); }
From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java
@SuppressWarnings("SleepWhileInLoop") // We are just using the sleep for rate limiting private void tsaRequest() throws Exception { final Random rand = new Random(); final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); boolean doRun = true; do {//from www .j a v a 2 s . com final int nonce = rand.nextInt(); byte[] digest = new byte[20]; if (instring != null) { final byte[] digestBytes = instring.getBytes("UTF-8"); final MessageDigest dig = MessageDigest.getInstance(TSPAlgorithms.SHA1.getId(), "BC"); dig.update(digestBytes); digest = dig.digest(); // When we have given input, we don't want to loop doRun = false; } if (infilestring != null) { // TSPAlgorithms constants changed from Strings to ASN1Encoded objects digest = digestFile(infilestring, TSPAlgorithms.SHA1.getId()); doRun = false; } final byte[] hexDigest = Hex.encode(digest); if (LOG.isDebugEnabled()) { LOG.debug("MessageDigest=" + new String(hexDigest)); } final TimeStampRequest timeStampRequest; if (inreqstring == null) { LOG.debug("Generating a new request"); timeStampRequestGenerator.setCertReq(certReq); if (reqPolicy != null) { timeStampRequestGenerator.setReqPolicy(new ASN1ObjectIdentifier(reqPolicy)); } timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest, BigInteger.valueOf(nonce)); } else { LOG.debug("Reading request from file"); timeStampRequest = new TimeStampRequest(readFiletoBuffer(inreqstring)); } final byte[] requestBytes = timeStampRequest.getEncoded(); if (outreqstring != null) { // Store request byte[] outBytes; if (base64) { outBytes = Base64.encode(requestBytes); } else { outBytes = requestBytes; } FileOutputStream fos = null; try { fos = new FileOutputStream(outreqstring); fos.write(outBytes); } finally { if (fos != null) { fos.close(); } } } keyStoreOptions.setupHTTPS(); URL url; URLConnection urlConn; DataOutputStream printout; DataInputStream input; url = new URL(urlstring); // Take start time final long startMillis = System.currentTimeMillis(); final long startTime = System.nanoTime(); if (LOG.isDebugEnabled()) { LOG.debug("Sending request at: " + startMillis); } urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/timestamp-query"); // Send POST output. printout = new DataOutputStream(urlConn.getOutputStream()); printout.write(requestBytes); printout.flush(); printout.close(); // Get response data. input = new DataInputStream(urlConn.getInputStream()); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = input.read()) != -1) { baos.write(b); } // Take stop time final long estimatedTime = System.nanoTime() - startTime; LOG.info("Got reply after " + TimeUnit.NANOSECONDS.toMillis(estimatedTime) + " ms"); final byte[] replyBytes = baos.toByteArray(); if (outrepstring != null) { // Store request byte[] outBytes; if (base64) { outBytes = Base64.encode(replyBytes); } else { outBytes = replyBytes; } FileOutputStream fos = null; try { fos = new FileOutputStream(outrepstring); fos.write(outBytes); } finally { if (fos != null) { fos.close(); } } } final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes); timeStampResponse.validate(timeStampRequest); LOG.info("TimeStampRequest validated"); if (LOG.isDebugEnabled()) { final Date genTime; if (timeStampResponse.getTimeStampToken() != null && timeStampResponse.getTimeStampToken().getTimeStampInfo() != null) { genTime = timeStampResponse.getTimeStampToken().getTimeStampInfo().getGenTime(); } else { genTime = null; } LOG.debug("(Status: " + timeStampResponse.getStatus() + ", " + timeStampResponse.getFailInfo() + "): " + timeStampResponse.getStatusString() + (genTime != null ? (", genTime: " + genTime.getTime()) : "") + "\n"); } if (doRun) { Thread.sleep(sleep); } } while (doRun); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
/** * /*from w w w .ja va 2 s.c o m*/ * @param message * @param type set to 5 when sending a PKI request, 3 when sending a PKIConf * @return * @throws IOException * @throws NoSuchProviderException */ protected byte[] sendCmpTcp(byte[] message, int type) throws IOException, NoSuchProviderException { final String host = getProperty("tcpCmpProxyIP", this.CMP_HOST); final int port = getProperty("tcpCmpProxyPort", PORT_NUMBER); try { final Socket socket = new Socket(host, port); final byte[] msg = createTcpMessage(message); try { final BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream()); os.write(msg); os.flush(); DataInputStream dis = new DataInputStream(socket.getInputStream()); // Read the length, 32 bits final int len = dis.readInt(); log.info("Got a message claiming to be of length: " + len); // Read the version, 8 bits. Version should be 10 (protocol draft nr // 5) final int ver = dis.readByte(); log.info("Got a message with version: " + ver); assertEquals(ver, 10); // Read flags, 8 bits for version 10 final byte flags = dis.readByte(); log.info("Got a message with flags (1 means close): " + flags); // Check if the client wants us to close the connection (LSB is 1 in // that case according to spec) // Read message type, 8 bits final int msgType = dis.readByte(); log.info("Got a message of type: " + msgType); assertEquals(msgType, type); // Read message final ByteArrayOutputStream baos = new ByteArrayOutputStream(3072); while (dis.available() > 0) { baos.write(dis.read()); } log.info("Read " + baos.size() + " bytes"); final byte[] respBytes = baos.toByteArray(); assertNotNull(respBytes); assertTrue(respBytes.length > 0); return respBytes; } finally { socket.close(); } } catch (ConnectException e) { assertTrue("This test requires a CMP TCP listener to be configured on " + host + ":" + port + ". Edit conf/cmptcp.properties and redeploy.", false); } catch (EOFException e) { assertTrue("Response was malformed.", false); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } return null; }
From source file:com.max2idea.android.limbo.main.LimboActivity.java
public static String sendHttpGet(String url) { HttpConnection hcon = null;//from ww w . j av a2 s . co m DataInputStream dis = null; java.net.URL URL = null; try { URL = new java.net.URL(url); } catch (MalformedURLException ex) { Logger.getLogger(LimboActivity.class.getName()).log(Level.SEVERE, null, ex); } StringBuffer responseMessage = new StringBuffer(); try { // obtain a DataInputStream from the HttpConnection dis = new DataInputStream(URL.openStream()); // retrieve the response from the server int ch; while ((ch = dis.read()) != -1) { responseMessage.append((char) ch); } // end while ( ( ch = dis.read() ) != -1 ) } catch (Exception e) { e.printStackTrace(); responseMessage.append(e.getMessage()); } finally { try { if (hcon != null) { hcon.close(); } if (dis != null) { dis.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } // end try/catch } // end try/catch/finally return responseMessage.toString(); }
From source file:com.isecpartners.gizmo.HttpResponse.java
public void processResponse(InputStream in) throws FailedRequestException { StringBuffer content = new StringBuffer(); DataInputStream inputStream = new DataInputStream(in); ArrayByteList blist = new ArrayByteList(); String header = null;/*from ww w. j av a 2 s . co m*/ int contentLength = 0; boolean isChunked = false; String line; try { line = readline(inputStream); while (line != null && !line.equals(ENDL)) { content.append(line); if (line.toUpperCase().contains(CONTENT_LENGTH) && line.toUpperCase().indexOf(CONTENT_LENGTH) == 0) { String value = line.substring(line.indexOf(CONTENT_LENGTH) + CONTENT_LENGTH.length() + 2, line.indexOf('\r')); contentLength = Integer.parseInt(value.trim()); } else if (line.toUpperCase().contains(TRANSFER_ENCODING)) { if (line.toUpperCase() .substring( line.toUpperCase().indexOf(TRANSFER_ENCODING) + "Transfer-Encoding:".length()) .contains("CHUNKED")) { isChunked = true; } } else if (line.toUpperCase().contains(CONTENT_ENCODING)) { String value = line.substring(line.indexOf(CONTENT_ENCODING) + CONTENT_ENCODING.length() + 2, line.indexOf('\r')); value = value.trim(); if (value.toUpperCase().equals("GZIP")) { this.gzip = true; } else if (value.toUpperCase().equals("DEFLATE")) { this.deflate = true; } } line = readline(inputStream); } if (line == null) { GizmoView.log(content.toString()); throw new FailedRequestException(); } content.append("\r\n"); header = content.substring(0, content.indexOf("\r\n")); append(blist, content); if (contentLength != 0) { for (int ii = 0; ii < contentLength; ii++) { blist.add(inputStream.readByte()); } } if (isChunked) { boolean isDone = false; while (!isDone) { byte current = inputStream.readByte(); blist.add(current); int size = 0; while (current != '\n') { if (current != '\r') { size *= 16; if (Character.isLetter((char) current)) { current = (byte) Character.toLowerCase((char) current); } if ((current >= '0') && (current <= '9')) { size += (current - 48); } else if ((current >= 'a') && (current <= 'f')) { size += (10 + current - 97); } } current = inputStream.readByte(); while ((char) current == ' ') { current = inputStream.readByte(); } blist.add(current); } if (size != 0) { for (int ii = 0; ii < size; ii++) { int byte1 = inputStream.readByte(); byte blah = (byte) byte1; blist.add(blah); } blist.add(inputStream.readByte()); blist.add(inputStream.readByte()); } else { byte ch = (byte) inputStream.read(); StringBuffer endstuff = new StringBuffer(); blist.add(ch); endstuff.append((char) ch); while (ch != '\n') { ch = inputStream.readByte(); endstuff.append((char) ch); blist.add(ch); } isDone = true; } } } if (inputStream.available() > 0) { try { while (true) { blist.add(inputStream.readByte()); } } catch (EOFException e) { System.out.println(e); } } } catch (IOException ex) { Logger.getLogger(HttpResponse.class.getName()).log(Level.SEVERE, null, ex); } setBlist(blist); setHeader(header); if (this.gzip) { addContents(unzipData(blist.toArray())); } else if (this.deflate) { addContents(deflateData(blist.toArray())); } else { addContents(content.toString()); } }
From source file:VASSAL.tools.imports.adc2.MapBoard.java
@Override protected void load(File f) throws IOException { super.load(f); DataInputStream in = null; try {//from ww w . ja v a 2s .c o m in = new DataInputStream(new BufferedInputStream(new FileInputStream(f))); baseName = stripExtension(f.getName()); path = f.getPath(); int header = in.readByte(); if (header != -3) throw new FileFormatException("Invalid Mapboard File Header"); // don't know what these do. in.readFully(new byte[2]); // get the symbol set String s = readWindowsFileName(in); String symbolSetFileName = forceExtension(s, "set"); set = new SymbolSet(); File setFile = action.getCaseInsensitiveFile(new File(symbolSetFileName), f, true, new ExtensionFileFilter(ADC2Utils.SET_DESCRIPTION, new String[] { ADC2Utils.SET_EXTENSION })); if (setFile == null) throw new FileNotFoundException("Unable to find symbol set file."); set.importFile(action, setFile); in.readByte(); // ignored columns = ADC2Utils.readBase250Word(in); rows = ADC2Utils.readBase250Word(in); // presumably, they're all the same size (and they're square) int hexSize = set.getMapBoardSymbolSize(); // each block read separately readHexDataBlock(in); readPlaceNameBlock(in); readHexSideBlock(in); readLineDefinitionBlock(in); readAttributeBlock(in); readMapSheetBlock(in); readHexLineBlock(in); readLineDrawPriorityBlock(in); // end of data blocks int orientation = in.read(); switch (orientation) { case 0: case 1: // vertical hex orientation or grid offset column if (set.getMapBoardSymbolShape() == SymbolSet.Shape.SQUARE) layout = new GridOffsetColumnLayout(hexSize, columns, rows); else layout = new VerticalHexLayout(hexSize, columns, rows); break; case 2: // horizontal hex orientation or grid offset row if (set.getMapBoardSymbolShape() == SymbolSet.Shape.SQUARE) layout = new GridOffsetRowLayout(hexSize, columns, rows); else layout = new HorizontalHexLayout(hexSize, columns, rows); break; default: // square grid -- no offset layout = new GridLayout(hexSize, columns, rows); } /* int saveMapPosition = */ in.readByte(); /* int mapViewingPosition = */ in.readShort(); // probably base-250 /* int mapViewingZoomLevel = */ in.readShort(); in.readByte(); // totally unknown // strangely, more blocks readTableColorBlock(in); readHexNumberingBlock(in); // TODO: default map item drawing order appears to be different for different maps. try { // optional blocks readMapBoardOverlaySymbolBlock(in); readVersionBlock(in); readMapItemDrawingOrderBlock(in); readMapItemDrawFlagBlock(in); } catch (ADC2Utils.NoMoreBlocksException e) { } in.close(); } finally { IOUtils.closeQuietly(in); } }