public CombinedCipherOutputStream(OutputStream out, Cipher asym, String algorithm) throws IOException, GeneralSecurityException { super(out); // create a new symmetric cipher key used for this stream String keyAlgorithm = getKeyAlgorithm(algorithm); SecretKey symKey = KeyGenerator.getInstance(keyAlgorithm).generateKey(); // place the symmetric key by encrypting it with asymmetric cipher out.write(asym.doFinal(symKey.getEncoded())); // the rest of the data will be encrypted by this symmetric cipher Cipher sym = Secret.getCipher(algorithm); sym.init(Cipher.ENCRYPT_MODE,symKey, keyAlgorithm.equals(algorithm) ? null : new IvParameterSpec(symKey.getEncoded())); super.out = new CipherOutputStream(out,sym); }
/** * Upgrades a connection with transport encryption by the specified symmetric cipher. * * @return * A new {@link Connection} object that includes the transport encryption. */ public Connection encryptConnection(SecretKey sessionKey, String algorithm) throws IOException, GeneralSecurityException { Cipher cout = Cipher.getInstance(algorithm); cout.init(Cipher.ENCRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded())); CipherOutputStream o = new CipherOutputStream(out, cout); Cipher cin = Cipher.getInstance(algorithm); cin.init(Cipher.DECRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded())); CipherInputStream i = new CipherInputStream(in, cin); return new Connection(i,o); }
@Override public OutputStream createEncryptionStream(OutputStream out) { if (!initialized) { init(); } return new javax.crypto.CipherOutputStream(out, cipher); }
/** * Returns the output stream for writing the data.<p> * Make sure to close it, otherwise the last cipher block is not written completely. * * @return the outputstream * @throws IOException if the writing to the underlying file fails */ public OutputStream getOutputStream() throws IOException { Cipher ciEnc = CryptoFunctions.getCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.ENCRYPT_MODE, PADDING); return new CipherOutputStream(new FileOutputStream(tempFile), ciEnc); }
@SuppressWarnings("resource") private StandardCipherOutputStream(DirectoryNode dir, File fileOut) throws IOException { // although not documented, we need the same padding as with agile encryption // and instead of calculating the missing bytes for the block size ourselves // we leave it up to the CipherOutputStream, which generates/saves them on close() // ... we can't use "NoPadding" here // // see also [MS-OFFCRYPT] - 2.3.4.15 // The final data block MUST be padded to the next integral multiple of the // KeyData.blockSize value. Any padding bytes can be used. Note that the StreamSize // field of the EncryptedPackage field specifies the number of bytes of // unencrypted data as specified in section 2.3.4.4. super( new CipherOutputStream(new FileOutputStream(fileOut), getCipher(getSecretKey(), "PKCS5Padding")) ); this.fileOut = fileOut; this.dir = dir; }
/** * Persists the payload of {@link ConfidentialKey} to the disk. */ @Override protected void store(ConfidentialKey key, byte[] payload) throws IOException { try { Cipher sym = Secret.getCipher("AES"); sym.init(Cipher.ENCRYPT_MODE, masterKey); try (OutputStream fos = Files.newOutputStream(getFileFor(key).toPath()); CipherOutputStream cos = new CipherOutputStream(fos, sym)) { cos.write(payload); cos.write(MAGIC); } } catch (GeneralSecurityException e) { throw new IOException("Failed to persist the key: "+key.getId(),e); } catch (InvalidPathException e) { throw new IOException(e); } }
public long writeHtmlTo(long start, Writer w) throws IOException { ConsoleAnnotationOutputStream<T> caw = new ConsoleAnnotationOutputStream<>( w, createAnnotator(Stapler.getCurrentRequest()), context, charset); long r = super.writeLogTo(start,caw); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Cipher sym = PASSING_ANNOTATOR.encrypt(); ObjectOutputStream oos = AnonymousClassWarnings.checkingObjectOutputStream(new GZIPOutputStream(new CipherOutputStream(baos,sym))); oos.writeLong(System.currentTimeMillis()); // send timestamp to prevent a replay attack oos.writeObject(caw.getConsoleAnnotator()); oos.close(); StaplerResponse rsp = Stapler.getCurrentResponse(); if (rsp!=null) rsp.setHeader("X-ConsoleAnnotator", new String(Base64.encode(baos.toByteArray()))); return r; }
_cipher.init(Cipher.ENCRYPT_MODE, sharedKey); _cipherOut = new CipherOutputStream(_bodyOut, _cipher); } catch (RuntimeException e) { throw e;
@Override protected OutputStream decorateOutputStream(FileOutputStream fos) { init(); Cipher ciEnc = CryptoFunctions.getCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.ENCRYPT_MODE, "PKCS5Padding"); return new CipherOutputStream(fos, ciEnc); }
protected StandardCipherOutputStream(DirectoryNode dir) throws IOException { super(null); this.dir = dir; fileOut = TempFile.createTempFile("encrypted_package", "crypt"); FileOutputStream rawStream = new FileOutputStream(fileOut); // although not documented, we need the same padding as with agile encryption // and instead of calculating the missing bytes for the block size ourselves // we leave it up to the CipherOutputStream, which generates/saves them on close() // ... we can't use "NoPadding" here // // see also [MS-OFFCRYPT] - 2.3.4.15 // The final data block MUST be padded to the next integral multiple of the // KeyData.blockSize value. Any padding bytes can be used. Note that the StreamSize // field of the EncryptedPackage field specifies the number of bytes of // unencrypted data as specified in section 2.3.4.4. CipherOutputStream cryptStream = new CipherOutputStream(rawStream, getCipher(getSecretKey(), "PKCS5Padding")); this.out = cryptStream; }
output = new DataOutputStream(new CipherOutputStream(bufferedOutputStream, cipher));
initCipher(); final OutputStream base64OutputStream = getBase64Stream(origStream); final CipherOutputStream encryptedStream = new CipherOutputStream(base64OutputStream, cipher);
private static byte[] encryptWithAesGcm(byte[] plaintext, byte[] randomKeyBytes, byte[] randomIvBytes) throws IOException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException { SecretKey randomKey = new SecretKeySpec(randomKeyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, randomKey, new IvParameterSpec(randomIvBytes)); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(byteArrayOutputStream, cipher); cipherOutputStream.write(plaintext); cipherOutputStream.close(); return byteArrayOutputStream.toByteArray(); }
public void close() {} }; CipherOutputStream cos = new CipherOutputStream(fos2, ciEnc); IOUtils.copy(zis, cos); cos.close();
socketOut = cipherOutputStream = new CipherOutputStream( bufferedOutputStream, decryptionCip ); } catch ( InvalidKeyException ex ) { baseStep.logError( "Invalid key was received", ex );
@Override OutputStream encrypt(OutputStream os) throws IOException { try { final Cipher cipher = InsecureCipherFactory.create(cryptoAlg); cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec); return new CipherOutputStream(os, cipher); } catch (GeneralSecurityException e) { throw error(e); } }
/** Encrypt the keystore entries and return the encrypted data. */ private byte[] encrypt(char[] password, byte[] salt, byte[] iv) throws GeneralSecurityException, IOException { assert isLoaded(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); Cipher cipher = createCipher(Cipher.ENCRYPT_MODE, password, salt, iv); try (CipherOutputStream cipherStream = new CipherOutputStream(bytes, cipher); DataOutputStream output = new DataOutputStream(cipherStream)) { output.writeInt(entries.get().size()); for (Map.Entry<String, Entry> mapEntry : entries.get().entrySet()) { output.writeUTF(mapEntry.getKey()); Entry entry = mapEntry.getValue(); output.writeUTF(entry.type.name()); output.writeInt(entry.bytes.length); output.write(entry.bytes); } } return bytes.toByteArray(); }
private static byte[] encryptBlocks(final byte[] data, final Cipher cipher, final int dataSize) throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length); final int count = (data.length / dataSize) + 1; int remaining = data.length; for (int i=0; i<count; i++) { final int offset = i*dataSize; final int length = Math.min(dataSize, remaining); final CipherOutputStream cos = new CipherOutputStream(bos, cipher); cos.write(data, offset, length); cos.flush(); cos.close(); remaining -= length; } return bos.toByteArray(); }
@Override OutputStream encrypt(OutputStream output) throws IOException { try { Cipher cipher = InsecureCipherFactory.create(cipherAlgo); cipher.init(Cipher.ENCRYPT_MODE, secretKey); AlgorithmParameters params = cipher.getParameters(); if (params == null) { context = EMPTY; } else { context = Base64.encodeBytes(params.getEncoded()); } return new CipherOutputStream(output, cipher); } catch (Exception e) { throw error(e); } }
@SuppressWarnings("PMD.UnusedPrivateMethod") // false positive private static <T> void saveEncryptedJsonToFile(String fileName, T object, Type typeOfObject) throws Exception { SecretKeySpec sks = new SecretKeySpec(StringHelper.hexStringToByteArray(Config.ENCRYPTION_KEY), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters()); try (OutputStream os = Files.newOutputStream(Paths.get(fileName))) { CipherOutputStream out = new CipherOutputStream(os, cipher); JsonWriter writer = new JsonWriter(new OutputStreamWriter(out)); getSerializer().toJson(object, typeOfObject, writer); writer.close(); out.close(); } }