List of usage examples for javax.crypto CipherInputStream CipherInputStream
public CipherInputStream(InputStream is, Cipher c)
From source file:org.zuinnote.hadoop.office.format.common.writer.msexcel.internal.EncryptedZipEntrySource.java
@Override public InputStream getInputStream(ZipArchiveEntry entry) throws IOException { InputStream is = this.zipFile.getInputStream(entry); if (this.ciDecoder != null) { return new CipherInputStream(is, this.ciDecoder); }/*from w w w .ja v a 2s. co m*/ return is; }
From source file:org.yes.cart.shoppingcart.support.impl.AbstractCryptedTuplizerImpl.java
/** * Convert string tuple back to the original object. * * @param tuple string tuple//from ww w .j av a2s. c om * * @return cart object of null * * @throws CartDetuplizationException when cannot deserialize the object */ protected ShoppingCart toObject(String tuple) throws CartDetuplizationException { if (tuple == null || tuple.length() == 0) { return null; } final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tuple.getBytes()); final Base64InputStream base64DecoderStream = new Base64InputStream(byteArrayInputStream); final CipherInputStream cipherInputStream = new CipherInputStream(base64DecoderStream, desUnCipher); ObjectInputStream objectInputStream = null; try { objectInputStream = new ObjectInputStream(cipherInputStream); return (ShoppingCart) objectInputStream.readObject(); } catch (Exception exception) { try { desUnCipher.init(Cipher.DECRYPT_MODE, secretKey); //reinit } catch (InvalidKeyException e) { LOG.error("Cant reinit desUnCipher", exception); } final String errMsg = "Unable to convert bytes assembled from tuple into object"; LOG.error(errMsg, exception); throw new CartDetuplizationException(errMsg, exception); } finally { try { if (objectInputStream != null) { objectInputStream.close(); } cipherInputStream.close(); base64DecoderStream.close(); byteArrayInputStream.close(); } catch (IOException ioe) { // leave this one silent as we have the object. LOG.error("Unable to close object stream", ioe); } } }
From source file:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java
/** * creates a reader which depends on the configured fileEncoding for DesignSync * F000037B2/*from w w w .j a v a 2s. c o m*/ * @param file * @return * @throws UnsupportedEncodingException * @throws FileNotFoundException * @throws FileSystemException */ protected Reader createReader(FileObject file) throws UnsupportedEncodingException, FileNotFoundException, FileSystemException { InputStream in = file.getContent().getInputStream(); // If obfuscation enabled, use cipher to read code/metadata of script and tml deployments DESEncrypter cipher = getManager().getCipher(); if (cipher != null && (getType() == WGDocument.TYPE_TML || getType() == WGDocument.TYPE_CSSJS)) { in = new CipherInputStream(in, cipher.getDcipher()); } String encoding = getManager().getFileEncoding(); // No more used because this creates a lot of problems with empty files // CharsetDecoder deco = Charset.forName(encoding).newDecoder(); // deco.onMalformedInput(CodingErrorAction.REPORT); // deco.onUnmappableCharacter(CodingErrorAction.REPORT); return new BufferedReader(new InputStreamReader(in, encoding)); }
From source file:org.wso2.carbon.apimgt.core.impl.FileEncryptionUtility.java
/** * Decrypts the content of an encrypted file and returns the text * * @param inputFilePath absolute path of the encrypted file * @return content of the file after decryption * @throws APIManagementException if an error occurs while reading from the encrypted file *///from w w w. j av a 2 s. com public String readFromEncryptedFile(String inputFilePath) throws APIManagementException { CipherInputStream cipherInStream = null; ByteArrayOutputStream byteArrayOutStream = null; try { if (!Files.exists(Paths.get(inputFilePath))) { throw new APIManagementException("File to decrypt does not exist"); } Cipher aesCipher = Cipher.getInstance(EncryptionConstants.AES); SecretKeySpec aesKeySpec = new SecretKeySpec(getAESKey(), EncryptionConstants.AES); aesCipher.init(Cipher.DECRYPT_MODE, aesKeySpec); cipherInStream = new CipherInputStream(APIFileUtils.readFileContentAsStream(inputFilePath), aesCipher); byteArrayOutStream = new ByteArrayOutputStream(); IOUtils.copy(cipherInStream, byteArrayOutStream); byte[] outByteArray = byteArrayOutStream.toByteArray(); log.debug("Successfully decrypted file using stored AES key"); return new String(SecureVaultUtils.toChars(outByteArray)); } catch (IOException | InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException e) { String msg = "Error while decrypting file " + inputFilePath; throw new APIManagementException(msg, e); } finally { IOUtils.closeQuietly(cipherInStream); IOUtils.closeQuietly(byteArrayOutStream); } }
From source file:org.structr.cloud.CloudConnection.java
@Override public void start() { // setup read and write threads for the connection if (socket.isConnected() && !socket.isClosed()) { try {/*from w ww. j ava 2s . c o m*/ decrypter = Cipher.getInstance(CloudService.STREAM_CIPHER); encrypter = Cipher.getInstance(CloudService.STREAM_CIPHER); // this key is only used for the first two packets // of a transmission, it is replaced by the users // password hash afterwards. setEncryptionKey("StructrInitialEncryptionKey", 128); sender = new Sender(this, new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream( new CipherOutputStream(socket.getOutputStream(), encrypter), 32768, true)))); receiver = new Receiver(this, new DataInputStream(new BufferedInputStream( new GZIPInputStream(new CipherInputStream(socket.getInputStream(), decrypter), 32768)))); receiver.start(); sender.start(); // start actual thread super.start(); } catch (Throwable t) { t.printStackTrace(); } } }
From source file:gobblin.crypto.RotatingAESCodecTest.java
private void manuallyDecodeAndVerifyBytes(byte[] originalBytes, byte[] encryptedBytes, SimpleCredentialStore credStore) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { // Manually decode InputStream in = new ByteArrayInputStream(encryptedBytes); verifyKeyId(in, 1);/* w w w . j a va2 s . c o m*/ Integer ivLen = verifyIvLen(in); byte[] ivBinary = verifyAndExtractIv(in, ivLen); byte[] body = readAndBase64DecodeBody(in); // feed back into cipheroutput stream Cipher inputCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBinary); inputCipher.init(Cipher.DECRYPT_MODE, credStore.getKey(), ivParameterSpec); CipherInputStream cis = new CipherInputStream(new ByteArrayInputStream(body), inputCipher); byte[] decoded = IOUtils.toByteArray(cis); Assert.assertEquals(decoded, originalBytes, "Expected decoded output to match encoded output"); }
From source file:it.doqui.index.ecmengine.business.personalization.encryption.content.DecryptingContentReaderDecorator.java
public InputStream getContentInputStream() throws ContentIOException { logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] BEGIN"); IvParameterSpec iv = null;//w w w. j a va2 s . co m try { Cipher cipher = null; try { cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec), "SunJCE"); } catch (NoSuchProviderException e) { logger.warn( "[DecryptingContentReaderDecorator::getContentInputStream] Unknown provider \"SunJCE\". Using default..."); cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec)); } if (transformationSpec.getMode() != null && !transformationSpec.getMode().equalsIgnoreCase("ECB")) { iv = new IvParameterSpec(transformationSpec.getIv()); logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] IvParameterSpec: " + iv); cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); } else { cipher.init(Cipher.DECRYPT_MODE, secretKey); } logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] " + "Cipher initialized: DECRYPT - " + cipher.getProvider() + " - " + cipher.getAlgorithm()); CipherInputStream cis = new CipherInputStream(reader.getContentInputStream(), cipher); return cis; } catch (NoSuchPaddingException e) { logger.warn("[DecryptingContentReaderDecorator::getContentInputStream] Invalid padding: " + transformationSpec.getPadding()); throw new EncryptionRuntimeException("Invalid padding: " + transformationSpec.getPadding(), e); } catch (NoSuchAlgorithmException e) { logger.warn("[DecryptingContentReaderDecorator::getContentInputStream] Invalid algorithm: " + transformationSpec.getAlgorithm()); throw new EncryptionRuntimeException("Invalid algorithm: " + transformationSpec.getAlgorithm(), e); } catch (InvalidKeyException e) { logger.warn("[DecryptingContentReaderDecorator::getContentInputStream] Invalid key!"); throw new EncryptionRuntimeException("Invalid key!", e); } catch (InvalidAlgorithmParameterException e) { logger.warn( "[DecryptingContentReaderDecorator::getContentInputStream] Invalid algorithm parameter: " + iv); throw new EncryptionRuntimeException("Invalid algorithm parameter: " + iv, e); } finally { logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] END"); } }
From source file:org.apache.camel.converter.crypto.CryptoDataFormat.java
public Object unmarshal(Exchange exchange, InputStream encryptedStream) throws Exception { Object unmarshalled = null;/* www. j a va 2s. c om*/ if (encryptedStream != null) { byte[] iv = getInlinedInitializationVector(exchange, encryptedStream); Key key = getKey(exchange); CipherInputStream cipherStream = new CipherInputStream(encryptedStream, initializeCipher(DECRYPT_MODE, key, iv)); ByteArrayOutputStream plaintextStream = new ByteArrayOutputStream(bufferSize); HMACAccumulator hmac = getMessageAuthenticationCode(key); byte[] buffer = new byte[bufferSize]; hmac.attachStream(plaintextStream); int read; while ((read = cipherStream.read(buffer)) >= 0) { hmac.decryptUpdate(buffer, read); } hmac.validate(); unmarshalled = plaintextStream.toByteArray(); } return unmarshalled; }
From source file:org.openmrs.module.clinicalsummary.web.controller.upload.UploadSummariesController.java
public void validate(final String filename, final String password) throws Exception { String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED), "."); ZipFile encryptedFile = new ZipFile(new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename)); byte[] initVector = null; byte[] encryptedSampleBytes = null; Enumeration<? extends ZipEntry> entries = encryptedFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); String zipEntryName = zipEntry.getName(); if (zipEntryName.endsWith(TaskConstants.FILE_TYPE_SECRET)) { InputStream inputStream = encryptedFile.getInputStream(zipEntry); initVector = FileCopyUtils.copyToByteArray(inputStream); if (initVector.length != IV_SIZE) { throw new Exception("Secret file is corrupted or invalid secret file are being used."); }/* w w w. j ava2 s .c o m*/ } else if (zipEntryName.endsWith(TaskConstants.FILE_TYPE_SAMPLE)) { InputStream inputStream = encryptedFile.getInputStream(zipEntry); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileCopyUtils.copy(inputStream, baos); encryptedSampleBytes = baos.toByteArray(); } } if (initVector != null && encryptedSampleBytes != null) { SecretKeyFactory factory = SecretKeyFactory.getInstance(TaskConstants.SECRET_KEY_FACTORY); KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128); SecretKey tmp = factory.generateSecret(spec); // generate the secret key SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC); // create the cipher Cipher cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(initVector)); // decrypt the sample ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(encryptedSampleBytes); CipherInputStream cipherInputStream = new CipherInputStream(byteArrayInputStream, cipher); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileCopyUtils.copy(cipherInputStream, baos); String sampleText = baos.toString(); if (!sampleText.contains("This is sample text")) { throw new Exception("Upload parameters incorrect!"); } } }
From source file:oscar.oscarLab.ca.all.pageUtil.LabUploadAction.java
public static InputStream decryptMessage(InputStream is, String skey, PublicKey pkey) { Base64 base64 = new Base64(0); // Decrypt the secret key and the message try {/*from w w w. j a v a 2s .c o m*/ // retrieve the servers private key PrivateKey key = getServerPrivate(); // Decrypt the secret key using the servers private key Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] newSecretKey = cipher.doFinal(base64.decode(skey.getBytes(MiscUtils.ENCODING))); // Decrypt the message using the secret key SecretKeySpec skeySpec = new SecretKeySpec(newSecretKey, "AES"); Cipher msgCipher = Cipher.getInstance("AES"); msgCipher.init(Cipher.DECRYPT_MODE, skeySpec); is = new CipherInputStream(is, msgCipher); // Return the decrypted message return (new BufferedInputStream(is)); } catch (Exception e) { logger.error("Could not decrypt the message", e); return (null); } }