List of usage examples for java.io ByteArrayInputStream read
public int read(byte b[]) throws IOException
b
. From source file:com.medicaid.mmis.util.DataLoader.java
private String readField(ByteArrayInputStream stream, ColumnDef def) throws PortalServiceException { byte[] buf = new byte[def.getWidth()]; try {//from w w w. j a v a 2s. c om int res = stream.read(buf); if (res < 1) { logger.debug("Reached end of line for record. No bytes to read " + def.name()); return ""; } } catch (IOException e) { // should not really happen on ByteArrayInputStream logger.warn("Could not read from in-memory buffer."); } String value = new String(buf); if (StringUtils.isNotBlank(value)) { logger.debug("Read: " + def.name() + " : " + value); return value.trim(); } return ""; }
From source file:com.maverick.ssl.SSLHandshakeProtocol.java
private void onServerHelloDoneMsg() throws SSLException { // Generate the premaster secret calculatePreMasterSecret();// w w w. ja va2 s . co m byte[] secret = null; try { // Encrypt the premaster secret BigInteger input = new BigInteger(1, premasterSecret); PublicKey key = x509.getPublicKey(); if (key instanceof RsaPublicKey) { BigInteger padded = Rsa.padPKCS1(input, 0x02, 128); BigInteger s = Rsa.doPublic(padded, ((RsaPublicKey) key).getModulus(), ((RsaPublicKey) key).getPublicExponent()); secret = s.toByteArray(); } else { throw new SSLException(SSLException.UNSUPPORTED_CERTIFICATE); } } catch (CertificateException ex) { throw new SSLException(SSLException.UNSUPPORTED_CERTIFICATE, ex.getMessage()); } if (secret[0] == 0) { byte[] tmp = new byte[secret.length - 1]; System.arraycopy(secret, 1, tmp, 0, secret.length - 1); secret = tmp; } sendMessage(CLIENT_KEY_EXCHANGE_MSG, secret); // Calculate the master secret calculateMasterSecret(); // #ifdef DEBUG log.debug(Messages.getString("SSLHandshakeProtocol.generatingKeyData")); //$NON-NLS-1$ // #endif // Generate the keys etc and put the cipher into use byte[] keydata; int length = 0; length += pendingCipherSuite.getKeyLength() * 2; length += pendingCipherSuite.getMACLength() * 2; length += pendingCipherSuite.getIVLength() * 2; ByteArrayOutputStream out = new ByteArrayOutputStream(); MD5Digest md5 = new MD5Digest(); SHA1Digest sha1 = new SHA1Digest(); int turn = 0; while (out.size() < length) { md5.reset(); sha1.reset(); for (int i = 0; i <= turn; i++) { sha1.update((byte) ('A' + turn)); } sha1.update(masterSecret, 0, masterSecret.length); sha1.update(serverRandom, 0, serverRandom.length); sha1.update(clientRandom, 0, clientRandom.length); md5.update(masterSecret, 0, masterSecret.length); byte[] tmp = new byte[sha1.getDigestSize()]; sha1.doFinal(tmp, 0); md5.update(tmp, 0, tmp.length); tmp = new byte[md5.getDigestSize()]; md5.doFinal(tmp, 0); // Write out a block of key data out.write(tmp, 0, tmp.length); turn++; } keydata = out.toByteArray(); ByteArrayInputStream in = new ByteArrayInputStream(keydata); byte[] encryptKey = new byte[pendingCipherSuite.getKeyLength()]; byte[] encryptIV = new byte[pendingCipherSuite.getIVLength()]; byte[] encryptMAC = new byte[pendingCipherSuite.getMACLength()]; byte[] decryptKey = new byte[pendingCipherSuite.getKeyLength()]; byte[] decryptIV = new byte[pendingCipherSuite.getIVLength()]; byte[] decryptMAC = new byte[pendingCipherSuite.getMACLength()]; try { in.read(encryptMAC); in.read(decryptMAC); in.read(encryptKey); in.read(decryptKey); in.read(encryptIV); in.read(decryptIV); } catch (IOException ex) { throw new SSLException(SSLException.INTERNAL_ERROR, ex.getMessage() == null ? ex.getClass().getName() : ex.getMessage()); } pendingCipherSuite.init(encryptKey, encryptIV, encryptMAC, decryptKey, decryptIV, decryptMAC); currentHandshakeStep = SERVER_HELLO_DONE_MSG; // Send the change cipher spec socket.sendCipherChangeSpec(pendingCipherSuite); // Send the finished msg sendHandshakeFinished(); }
From source file:org.kontalk.crypto.Coder.java
/** * Creates encrypted and signed message body. * Errors that may occur are saved to the message. * @param message/* w w w .j a v a2s . c o m*/ * @return the encrypted and signed text. */ public static Optional<byte[]> processOutMessage(OutMessage message) { if (message.getCoderStatus().getEncryption() != Encryption.DECRYPTED) { LOGGER.warning("message does not want to be encrypted"); return Optional.empty(); } LOGGER.info("encrypting message..."); // get keys KeysResult keys = getKeys(message.getUser()); if (keys.myKey == null || keys.otherKey == null) { message.setSecurityErrors(keys.errors); return Optional.empty(); } // secure the message against the most basic attacks using Message/CPIM String from = keys.myKey.getUserId(); String to = keys.otherKey.userID + "; "; String mime = "text/plain"; // TODO encrypt more possible content String text = message.getContent().getPlainText(); CPIMMessage cpim = new CPIMMessage(from, to, new Date(), mime, text); byte[] plainText; try { plainText = cpim.toByteArray(); } catch (UnsupportedEncodingException ex) { LOGGER.log(Level.WARNING, "UTF-8 not supported", ex); plainText = cpim.toString().getBytes(); } // setup data encryptor & generator BcPGPDataEncryptorBuilder encryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_192); encryptor.setWithIntegrityPacket(true); encryptor.setSecureRandom(new SecureRandom()); // add public key recipients PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encryptor); //for (PGPPublicKey rcpt : mRecipients) encGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(keys.otherKey.encryptKey)); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(plainText); try { // catch all io and pgp exceptions OutputStream encryptedOut = encGen.open(out, new byte[BUFFER_SIZE]); // setup compressed data generator PGPCompressedDataGenerator compGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); OutputStream compressedOut = compGen.open(encryptedOut, new byte[BUFFER_SIZE]); // setup signature generator int algo = keys.myKey.getPublicEncryptionKey().getAlgorithm(); PGPSignatureGenerator sigGen = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(algo, HashAlgorithmTags.SHA1)); sigGen.init(PGPSignature.BINARY_DOCUMENT, keys.myKey.getPrivateEncryptionKey()); PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, keys.myKey.getUserId()); sigGen.setUnhashedSubpackets(spGen.generate()); sigGen.generateOnePassVersion(false).encode(compressedOut); // Initialize literal data generator PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator(); OutputStream literalOut = literalGen.open(compressedOut, PGPLiteralData.BINARY, "", new Date(), new byte[BUFFER_SIZE]); // read the "in" stream, compress, encrypt and write to the "out" stream // this must be done if clear data is bigger than the buffer size // but there are other ways to optimize... byte[] buf = new byte[BUFFER_SIZE]; int len; while ((len = in.read(buf)) > 0) { literalOut.write(buf, 0, len); try { sigGen.update(buf, 0, len); } catch (SignatureException ex) { LOGGER.log(Level.WARNING, "can't read data for signature", ex); message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA)); return Optional.empty(); } } in.close(); literalGen.close(); // generate the signature, compress, encrypt and write to the "out" stream try { sigGen.generate().encode(compressedOut); } catch (SignatureException ex) { LOGGER.log(Level.WARNING, "can't create signature", ex); message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA)); return Optional.empty(); } compGen.close(); encGen.close(); } catch (IOException | PGPException ex) { LOGGER.log(Level.WARNING, "can't encrypt message", ex); message.setSecurityErrors(EnumSet.of(Error.UNKNOWN_ERROR)); return Optional.empty(); } LOGGER.info("encryption successful"); return Optional.of(out.toByteArray()); }
From source file:big.BigZip.java
/** * Copies one file into the big archive * @param fileToCopy//from w ww . jav a 2 s. c o m * @return */ public boolean writeFile(final File fileToCopy) { // declare ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream(); try { /* Create Archive Output Stream that attaches File Output Stream / and specifies type of compression */ ArchiveOutputStream logical_zip = new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream); /* Create Archieve entry - write header information*/ logical_zip.putArchiveEntry(new ZipArchiveEntry(fileToCopy.getName())); /* Copy input file */ IOUtils.copy(new FileInputStream(fileToCopy), logical_zip); logical_zip.closeArchiveEntry(); logical_zip.finish(); logical_zip.flush(); logical_zip.close(); // get the bytes final ByteArrayInputStream byteInput = new ByteArrayInputStream(outputZipStream.toByteArray()); byte[] buffer = new byte[8192]; int length, counter = 0; // add the magic number to this file block outputStream.write(magicSignature.getBytes()); // now copy the whole file into the BIG archive while ((length = byteInput.read(buffer)) > 0) { outputStream.write(buffer, 0, length); counter += length; } // if there is something else to be flushed, do it now outputStream.flush(); // calculate the base path final String resultingPath = fileToCopy.getAbsolutePath().replace(basePath, ""); // calculate the SHA1 signature final String output = utils.hashing.checksum.generateFileChecksum("SHA-1", fileToCopy); // write a new line in our index file writerFileIndex.write( "\n" + utils.files.getPrettyFileSize(currentPosition) + " " + output + " " + resultingPath); // increase the position counter currentPosition += counter + magicSignature.length(); } catch (Exception e) { System.err.println("BIG346 - Error copying file: " + fileToCopy.getAbsolutePath()); return false; } finally { } return true; }
From source file:big.BigZip.java
/** * Copies one file into the big archive//from w ww . j a v a 2 s . com * @param fileToCopy * @param SHA1 * @param filePathToWriteInTextLine * @return */ public boolean quickWrite(final File fileToCopy, final String SHA1, final String filePathToWriteInTextLine) { // declare ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream(); try { // save this operation on the log of commits addTagStarted(fileToCopy.getName()); //pointRestoreAndSave(fileToCopy); /* Create Archive Output Stream that attaches File Output Stream / and specifies type of compression */ ArchiveOutputStream logical_zip = new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream); /* Create Archieve entry - write header information*/ logical_zip.putArchiveEntry(new ZipArchiveEntry(fileToCopy.getName())); /* Copy input file */ IOUtils.copy(new FileInputStream(fileToCopy), logical_zip); logical_zip.closeArchiveEntry(); logical_zip.finish(); logical_zip.flush(); logical_zip.close(); // get the bytes final ByteArrayInputStream byteInput = new ByteArrayInputStream(outputZipStream.toByteArray()); byte[] buffer = new byte[8192]; int length, counter = 0; // add the magic number to this file block outputStream.write(magicSignature.getBytes()); // now copy the whole file into the BIG archive while ((length = byteInput.read(buffer)) > 0) { outputStream.write(buffer, 0, length); counter += length; } // if there is something else to be flushed, do it now //outputStream.flush(); // calculate the base path //final String resultingPath = fileToCopy.getAbsolutePath().replace(rootFolder, ""); final String line = "\n" + utils.files.getPrettyFileSize(currentPosition) + " " + SHA1 + " " + filePathToWriteInTextLine; // write a new line in our index file writerFileIndex.write(line); //writer.flush(); // increase the position counter currentPosition += counter + magicSignature.length(); // close the log with success addTagEnded(); } catch (Exception e) { System.err.println("BIG600 - Error copying file: " + fileToCopy.getAbsolutePath()); return false; } finally { } return true; }
From source file:org.openbravo.erpCommon.obps.ActivationKey.java
private boolean decrypt(byte[] bytes, PublicKey pk, ByteArrayOutputStream bos, String strOBPublicKey) throws Exception { PublicKey obPk = getPublicKey(strOBPublicKey); // get OB public key to check signature Signature signer = Signature.getInstance("MD5withRSA"); signer.initVerify(obPk);//from ww w . jav a 2s . c o m Cipher cipher = Cipher.getInstance("RSA"); ByteArrayInputStream bis = new ByteArrayInputStream( org.apache.commons.codec.binary.Base64.decodeBase64(bytes)); // Encryptation only accepts 128B size, it must be chuncked final byte[] buf = new byte[128]; final byte[] signature = new byte[128]; // read the signature if (!(bis.read(signature) > 0)) { return false; } // decrypt while ((bis.read(buf)) > 0) { cipher.init(Cipher.DECRYPT_MODE, pk); bos.write(cipher.doFinal(buf)); } // verify signature signer.update(bos.toByteArray()); boolean signed = signer.verify(signature); log.debug("signature length:" + buf.length); log.debug("singature:" + (new BigInteger(signature).toString(16).toUpperCase())); log.debug("signed:" + signed); if (!signed) { isActive = false; errorMessage = "@NotSigned@"; setLogger(); return false; } return true; }
From source file:big.BigZip.java
/** * Copies one file into the big archive//from www .ja v a 2 s . c o m * @param stream * @param SHA1 * @param filePathToWriteInTextLine * @return * @throws java.io.IOException */ public boolean quickWriteGenericStream(final InputStream stream, final String SHA1, final String filePathToWriteInTextLine) throws IOException { // declare ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream(); ByteArrayInputStream byteInput = null; try { // save this operation on the log of commits addTagStarted(filePathToWriteInTextLine); // Create Archive Output Stream that attaches File Output Stream / and specifies type of compression ArchiveOutputStream logical_zip = new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream); // Create Archive entry - write header information ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(filePathToWriteInTextLine); logical_zip.putArchiveEntry(zipArchiveEntry); // Copy input file IOUtils.copy(stream, logical_zip); logical_zip.closeArchiveEntry(); logical_zip.finish(); logical_zip.flush(); logical_zip.close(); // get the bytes byteInput = new ByteArrayInputStream(outputZipStream.toByteArray()); byte[] buffer = new byte[8192]; int length, counter = 0; // add the magic number to this file block outputStream.write(magicSignature.getBytes()); // now copy the whole file into the BIG archive while ((length = byteInput.read(buffer)) > 0) { outputStream.write(buffer, 0, length); counter += length; } final String line = "\n" + utils.files.getPrettyFileSize(currentPosition) + " " + SHA1 + " " + filePathToWriteInTextLine; // write a new line in our index file writerFileIndex.write(line); //writer.flush(); // increase the position counter currentPosition += counter + magicSignature.length(); // close the log with success addTagEnded(); } catch (Exception e) { System.err.println("BIG600 - Error copying file: " + filePathToWriteInTextLine); return false; } finally { if (byteInput != null) { byteInput.close(); } stream.close(); outputZipStream.close(); outputStream.close(); } return true; }
From source file:big.BigZip.java
/** * Requires an InputStream, it will calculate the SHA1 checksum at the same * time that it writes data onto the big file. The input stream is expected * to be closed outside of this method.//from w w w. j a v a 2s . c o m * @param stream * @param filePathToWriteInTextLine * @throws java.io.IOException */ public void quickWriteStreamStandalone(final InputStream stream, final String filePathToWriteInTextLine) throws Exception { // declare ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream(); ByteArrayInputStream byteInput = null; // Create Archive Output Stream that attaches File Output Stream / and specifies type of compression ArchiveOutputStream logical_zip = new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream); // Create Archive entry - write header information ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(filePathToWriteInTextLine); logical_zip.putArchiveEntry(zipArchiveEntry); // prepare the SHA1 signature generation final MessageDigest hash = MessageDigest.getInstance("SHA1"); // Copy input file byte[] buffer = new byte[16384]; int length; // decompress from the original zip file, compress to our zip format // calculate the SHA1 signature on the same loop to save resource while ((length = stream.read(buffer)) > 0) { logical_zip.write(buffer, 0, length); hash.update(buffer, 0, length); } // compute the file signature byte[] digest = hash.digest(); final String SHA1 = utils.hashing.checksum.convertHash(digest); // close the zip related objects logical_zip.closeArchiveEntry(); logical_zip.finish(); logical_zip.flush(); logical_zip.close(); logical_zip = null; // define the line that will be written on the index file final String line = "\n".concat(utils.files.getPrettyFileSize(currentPosition)).concat(" ").concat(SHA1) .concat(" ").concat(filePathToWriteInTextLine); // get the bytes byteInput = new ByteArrayInputStream(outputZipStream.toByteArray()); int counter = 0; // add the magic number to this file block outputStream.write(magicSignature.getBytes()); // now copy the whole file into the BIG archive while ((length = byteInput.read(buffer)) > 0) { outputStream.write(buffer, 0, length); counter += length; } // write a new line in our index file writerFileIndex.write(line); // increase the position counter currentPosition += counter + magicSignature.length(); // close the streams that were created byteInput.close(); outputZipStream.close(); }
From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java
private boolean saveFileAtLocation(File downloadedFile, MessageData recvMsg) { try {//from w w w . j a v a 2 s . c o m File saveFile = downloadedFile; // make sure filename is unique int index = 1; while (saveFile.exists()) { saveFile = new File(SSUtil.getEnumeratedFilename(downloadedFile.getAbsolutePath(), index)); index++; } FileOutputStream f = new FileOutputStream(saveFile); ByteArrayInputStream in = new ByteArrayInputStream(recvMsg.getFileData()); byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = in.read(buffer)) > 0) { f.write(buffer, 0, len1); } f.close(); MessageDbAdapter dbMessage = MessageDbAdapter.openInstance(getApplicationContext()); if (!dbMessage.updateMessageFileLocation(recvMsg.getRowId(), saveFile.getName(), saveFile.getPath())) { showNote(R.string.error_UnableToUpdateMessageInDB); } // always show file automatically... showFileActionChooser(saveFile, recvMsg.getFileType()); return true; } catch (FileNotFoundException e) { showNote(e.getLocalizedMessage()); return false; } catch (SecurityException e) { showNote(e.getLocalizedMessage()); return false; } catch (IOException e) { showNote(e.getLocalizedMessage()); return false; } }
From source file:org.exoplatform.forum.service.impl.JCRDataStorage.java
public void importXML(String nodePath, ByteArrayInputStream bis, int typeImport) throws Exception { String nodeName = ""; byte[] bdata = new byte[bis.available()]; bis.read(bdata); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); ByteArrayInputStream is = new ByteArrayInputStream(bdata); Document doc = docBuilder.parse(is); doc.getDocumentElement().normalize(); String typeNodeExport = ((org.w3c.dom.Node) doc.getFirstChild().getChildNodes().item(0).getChildNodes() .item(0)).getTextContent();//from w ww. j a va 2 s . co m SessionProvider sProvider = CommonUtils.createSystemProvider(); List<String> patchNodeImport = new ArrayList<String>(); try { Node forumHome = getForumHomeNode(sProvider); is = new ByteArrayInputStream(bdata); if (!typeNodeExport.equals(EXO_FORUM_CATEGORY) && !typeNodeExport.equals(EXO_FORUM)) { // All nodes when import need reset childnode if (typeNodeExport.equals(EXO_CATEGORY_HOME)) { nodePath = getCategoryHome(sProvider).getPath(); Node categoryHome = getCategoryHome(sProvider); nodeName = "CategoryHome"; addDataFromXML(categoryHome, nodePath, sProvider, is, nodeName); } else if (typeNodeExport.equals(EXO_USER_PROFILE_HOME)) { Node userProfile = getUserProfileHome(sProvider); nodeName = "UserProfileHome"; nodePath = getUserProfileHome(sProvider).getPath(); addDataFromXML(userProfile, nodePath, sProvider, is, nodeName); } else if (typeNodeExport.equals(EXO_TAG_HOME)) { Node tagHome = getTagHome(sProvider); nodePath = getTagHome(sProvider).getPath(); nodeName = "TagHome"; addDataFromXML(tagHome, nodePath, sProvider, is, nodeName); } else if (typeNodeExport.equals(EXO_FORUM_BB_CODE_HOME)) { nodePath = dataLocator.getBBCodesLocation(); Node bbcodeNode = getBBCodesHome(sProvider); nodeName = "forumBBCode"; addDataFromXML(bbcodeNode, nodePath, sProvider, is, nodeName); } // Node import but don't need reset childnodes else if (typeNodeExport.equals(EXO_ADMINISTRATION_HOME)) { nodePath = getForumSystemHome(sProvider).getPath(); Node node = getAdminHome(sProvider); node.remove(); getForumSystemHome(sProvider).save(); typeImport = ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING; Session session = forumHome.getSession(); session.importXML(nodePath, is, typeImport); session.save(); } else if (typeNodeExport.equals(EXO_BAN_IP_HOME)) { nodePath = getForumSystemHome(sProvider).getPath(); Node node = getBanIPHome(sProvider); node.remove(); getForumSystemHome(sProvider).save(); typeImport = ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING; Session session = forumHome.getSession(); session.importXML(nodePath, is, typeImport); session.save(); } else { throw new RuntimeException("unknown type of node to export :" + typeNodeExport); } } else { if (typeNodeExport.equals(EXO_FORUM_CATEGORY)) { // Check if import forum but the data import have structure of a category --> Error if (nodePath.split("/").length == 6) { throw new ConstraintViolationException(); } nodePath = getCategoryHome(sProvider).getPath(); } Session session = forumHome.getSession(); NodeIterator iter = ((Node) session.getItem(nodePath)).getNodes(); while (iter.hasNext()) { patchNodeImport.add(iter.nextNode().getName()); } session.importXML(nodePath, is, typeImport); session.save(); NodeIterator newIter = ((Node) session.getItem(nodePath)).getNodes(); while (newIter.hasNext()) { Node node = newIter.nextNode(); if (patchNodeImport.contains(node.getName())) patchNodeImport.remove(node.getName()); else patchNodeImport.add(node.getName()); } } // update forum statistic and profile of owner post. if (typeNodeExport.equals(EXO_FORUM_CATEGORY) || typeNodeExport.equals(EXO_FORUM)) { for (String string : patchNodeImport) { updateForum(nodePath + "/" + string, false); } } else if (typeNodeExport.equals(EXO_CATEGORY_HOME)) { updateForum(null); } } finally { is.close(); } }