javax.crypto.CipherOutputStream Java Examples

The following examples show how to use javax.crypto.CipherOutputStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ModernEncryptingPartOutputStream.java    From mollyim-android with GNU General Public License v3.0 7 votes vote down vote up
public static Pair<byte[], OutputStream> createFor(@NonNull AttachmentSecret attachmentSecret, @NonNull File file, boolean inline)
    throws IOException
{
  byte[] random = new byte[32];
  new SecureRandom().nextBytes(random);

  try {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(attachmentSecret.getModernKey(), "HmacSHA256"));

    FileOutputStream fileOutputStream = new FileOutputStream(file);
    byte[]           iv               = new byte[16];
    byte[]           key              = mac.doFinal(random);

    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));

    if (inline) {
      fileOutputStream.write(random);
    }

    return new Pair<>(random, new CipherOutputStream(fileOutputStream, cipher));
  } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException e) {
    throw new AssertionError(e);
  }
}
 
Example #2
Source File: KeystoreTool.java    From secure-storage-android with Apache License 2.0 6 votes vote down vote up
@Nullable
static String encryptMessage(@NonNull Context context, @NonNull String plainMessage) throws SecureStorageException {
    try {
        Cipher input;
        if (VERSION.SDK_INT >= M) {
            input = Cipher.getInstance(KEY_TRANSFORMATION_ALGORITHM, KEY_CIPHER_MARSHMALLOW_PROVIDER);
        } else {
            input = Cipher.getInstance(KEY_TRANSFORMATION_ALGORITHM, KEY_CIPHER_JELLYBEAN_PROVIDER);
        }

        input.init(Cipher.ENCRYPT_MODE, getPublicKey(context));

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(
                outputStream, input);
        cipherOutputStream.write(plainMessage.getBytes(KEY_CHARSET));
        cipherOutputStream.close();

        byte[] values = outputStream.toByteArray();
        return Base64.encodeToString(values, Base64.DEFAULT);

    } catch (Exception e) {
        throw new SecureStorageException(e.getMessage(), e, KEYSTORE_EXCEPTION);
    }
}
 
Example #3
Source File: AndroidCryptoUtils.java    From zrtp-java with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public byte[] aesEncrypt(byte[] data, byte[] key, byte[] initVector)
		throws CryptoException {
	try {
		SecretKeySpec scs = new SecretKeySpec(key, "AES");
		Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding", "ZBC");
		IvParameterSpec iv = new IvParameterSpec(initVector);
		cipher.init(Cipher.ENCRYPT_MODE, scs, iv);
		ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
		CipherOutputStream out = new CipherOutputStream(baos, cipher);
		out.write(data, 0, data.length);
		out.close();
		baos.close();
		return baos.toByteArray();
	} catch (Exception e) {
		throw new CryptoException(e);
	}
}
 
Example #4
Source File: CipherStreamClose.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #5
Source File: StandardEncryptor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: ReadWriteSkip.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void runTest(BufferType bufType) throws IOException,
        GeneralSecurityException {

    ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
    try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
            decryptCipher)) {
        if (bufType == BufferType.BYTE_ARRAY_BUFFERING) {
            doByteTest(ciOutput);
        } else {
            doIntTest(ciOutput);
        }
    }

    check(plaintext, baOutput.toByteArray());
}
 
Example #7
Source File: WrongAAD.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void decryptWithEmptyAAD() throws Exception {
    System.out.println("decryptWithEmptyAAD() started");
    // initialize it with empty AAD to get exception during decryption
    Cipher decryptCipher = createCipher(Cipher.DECRYPT_MODE,
            encryptCipher.getParameters());
    try (ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
                    decryptCipher)) {
        if (decrypt(ciOutput, baOutput)) {
            throw new RuntimeException(
                    "Decryption has been perfomed successfully in"
                            + " spite of the decrypt Cipher has NOT been"
                            + " initialized with AAD");
        }
    }
    System.out.println("decryptWithEmptyAAD() passed");
}
 
Example #8
Source File: WrongAAD.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private void decryptWithEmptyAAD() throws Exception {
    System.out.println("decryptWithEmptyAAD() started");
    // initialize it with empty AAD to get exception during decryption
    Cipher decryptCipher = createCipher(Cipher.DECRYPT_MODE,
            encryptCipher.getParameters());
    try (ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
                    decryptCipher)) {
        if (decrypt(ciOutput, baOutput)) {
            throw new RuntimeException(
                    "Decryption has been perfomed successfully in"
                            + " spite of the decrypt Cipher has NOT been"
                            + " initialized with AAD");
        }
    }
    System.out.println("decryptWithEmptyAAD() passed");
}
 
Example #9
Source File: CICO_PBE_RW_Test.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The CICO PBE RW test specific part of the super.doTest(). Implements the
 * scenario in accordance to the class description.
 * @param type byteArrayBuffering or intByteBuffering
 * @throws IOException  any I/O operation failed.
 * @throws GeneralSecurityException any security error.
 */
@Override
public void proceedTest(String type) throws IOException,
        GeneralSecurityException {
    ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
    try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
            getDecryptCipher())) {
        if (type.equals(CICO_PBE_Test.BYTE_ARR_BUFFER)) {
            proceedTestUsingByteArrayBuffer(ciOutput);
        } else {
            proceedTestUsingIntBuffer(ciOutput);
        }
        ciOutput.flush();
    }
    // Compare input and output
    if (!TestUtilities.equalsBlock(plainText, baOutput.toByteArray(), TEXT_SIZE)) {
        throw new RuntimeException("outputText not same with expectedText"
                + " when test " + type);
    }
}
 
Example #10
Source File: WrongAAD.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void decryptWithEmptyAAD() throws Exception {
    System.out.println("decryptWithEmptyAAD() started");
    // initialize it with empty AAD to get exception during decryption
    Cipher decryptCipher = createCipher(Cipher.DECRYPT_MODE,
            encryptCipher.getParameters());
    try (ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
                    decryptCipher)) {
        if (decrypt(ciOutput, baOutput)) {
            throw new RuntimeException(
                    "Decryption has been perfomed successfully in"
                            + " spite of the decrypt Cipher has NOT been"
                            + " initialized with AAD");
        }
    }
    System.out.println("decryptWithEmptyAAD() passed");
}
 
Example #11
Source File: WrongAAD.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void decryptWithWrongAAD() throws Exception {
    System.out.println("decrypt with wrong AAD");

    // initialize it with wrong AAD to get an exception during decryption
    Cipher decryptCipher = createCipher(Cipher.DECRYPT_MODE,
            encryptCipher.getParameters());
    byte[] someAAD = Helper.generateBytes(AAD_SIZE + 1);
    decryptCipher.updateAAD(someAAD);

    // init output stream
    try (ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
                    decryptCipher);) {
        if (decrypt(ciOutput, baOutput)) {
            throw new RuntimeException(
                    "A decryption has been perfomed successfully in"
                            + " spite of the decrypt Cipher has been"
                            + " initialized with fake AAD");
        }
    }

    System.out.println("Passed");
}
 
Example #12
Source File: CICO_PBE_RW_Test.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The CICO PBE RW test specific part of the super.doTest(). Implements the
 * scenario in accordance to the class description.
 * @param type byteArrayBuffering or intByteBuffering
 * @throws IOException  any I/O operation failed.
 * @throws GeneralSecurityException any security error.
 */
@Override
public void proceedTest(String type) throws IOException,
        GeneralSecurityException {
    ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
    try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
            getDecryptCipher())) {
        if (type.equals(CICO_PBE_Test.BYTE_ARR_BUFFER)) {
            proceedTestUsingByteArrayBuffer(ciOutput);
        } else {
            proceedTestUsingIntBuffer(ciOutput);
        }
        ciOutput.flush();
    }
    // Compare input and output
    if (!TestUtilities.equalsBlock(plainText, baOutput.toByteArray(), TEXT_SIZE)) {
        throw new RuntimeException("outputText not same with expectedText"
                + " when test " + type);
    }
}
 
Example #13
Source File: CipherStreamClose.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #14
Source File: CipherStreamClose.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #15
Source File: ReadWriteSkip.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void runTest(BufferType bufType) throws IOException,
        GeneralSecurityException {

    ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
    try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
            decryptCipher)) {
        if (bufType == BufferType.BYTE_ARRAY_BUFFERING) {
            doByteTest(ciOutput);
        } else {
            doIntTest(ciOutput);
        }
    }

    check(plaintext, baOutput.toByteArray());
}
 
Example #16
Source File: ReadWriteSkip.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void runTest(BufferType bufType) throws IOException,
        GeneralSecurityException {

    ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
    try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
            decryptCipher)) {
        if (bufType == BufferType.BYTE_ARRAY_BUFFERING) {
            doByteTest(ciOutput);
        } else {
            doIntTest(ciOutput);
        }
    }

    check(plaintext, baOutput.toByteArray());
}
 
Example #17
Source File: CICO_PBE_RW_Test.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The CICO PBE RW test specific part of the super.doTest(). Implements the
 * scenario in accordance to the class description.
 * @param type byteArrayBuffering or intByteBuffering
 * @throws IOException  any I/O operation failed.
 * @throws GeneralSecurityException any security error.
 */
@Override
public void proceedTest(String type) throws IOException,
        GeneralSecurityException {
    ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
    try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
            getDecryptCipher())) {
        if (type.equals(CICO_PBE_Test.BYTE_ARR_BUFFER)) {
            proceedTestUsingByteArrayBuffer(ciOutput);
        } else {
            proceedTestUsingIntBuffer(ciOutput);
        }
        ciOutput.flush();
    }
    // Compare input and output
    if (!TestUtilities.equalsBlock(plainText, baOutput.toByteArray(), TEXT_SIZE)) {
        throw new RuntimeException("outputText not same with expectedText"
                + " when test " + type);
    }
}
 
Example #18
Source File: WrongAAD.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void decryptWithWrongAAD() throws Exception {
    System.out.println("decrypt with wrong AAD");

    // initialize it with wrong AAD to get an exception during decryption
    Cipher decryptCipher = createCipher(Cipher.DECRYPT_MODE,
            encryptCipher.getParameters());
    byte[] someAAD = Helper.generateBytes(AAD_SIZE + 1);
    decryptCipher.updateAAD(someAAD);

    // init output stream
    try (ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
                    decryptCipher);) {
        if (decrypt(ciOutput, baOutput)) {
            throw new RuntimeException(
                    "A decryption has been perfomed successfully in"
                            + " spite of the decrypt Cipher has been"
                            + " initialized with fake AAD");
        }
    }

    System.out.println("Passed");
}
 
Example #19
Source File: CipherStreamClose.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #20
Source File: ReadWriteSkip.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void runTest(BufferType bufType) throws IOException,
        GeneralSecurityException {

    ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
    try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
            decryptCipher)) {
        if (bufType == BufferType.BYTE_ARRAY_BUFFERING) {
            doByteTest(ciOutput);
        } else {
            doIntTest(ciOutput);
        }
    }

    check(plaintext, baOutput.toByteArray());
}
 
Example #21
Source File: WrongAAD.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void decryptWithEmptyAAD() throws Exception {
    System.out.println("decryptWithEmptyAAD() started");
    // initialize it with empty AAD to get exception during decryption
    Cipher decryptCipher = createCipher(Cipher.DECRYPT_MODE,
            encryptCipher.getParameters());
    try (ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
                    decryptCipher)) {
        if (decrypt(ciOutput, baOutput)) {
            throw new RuntimeException(
                    "Decryption has been perfomed successfully in"
                            + " spite of the decrypt Cipher has NOT been"
                            + " initialized with AAD");
        }
    }
    System.out.println("decryptWithEmptyAAD() passed");
}
 
Example #22
Source File: AesGcmNoPaddingCryptoAlgorithm.java    From kafka-encryption with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] encrypt(byte[] data, byte[] key) throws Exception {
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, KEY_SPEC);
    byte[] iv = new byte[IV_SIZE];
    secureRandom.nextBytes(iv);
    GCMParameterSpec gcmParamSpec = new GCMParameterSpec(TAG_BIT_LENGTH, iv);
    Cipher cipher = Cipher.getInstance(ALGO_TRANSFORMATION_STRING);
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmParamSpec, secureRandom);
    cipher.updateAAD(TAG.getBytes(StandardCharsets.UTF_8));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(iv);

    try (CipherOutputStream cipherOutputStream = new CipherOutputStream(baos, cipher)) {
        cipherOutputStream.write(data);
    }

    return baos.toByteArray();
}
 
Example #23
Source File: ReadWriteSkip.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void runTest(BufferType bufType) throws IOException,
        GeneralSecurityException {

    ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
    try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
            decryptCipher)) {
        if (bufType == BufferType.BYTE_ARRAY_BUFFERING) {
            doByteTest(ciOutput);
        } else {
            doIntTest(ciOutput);
        }
    }

    check(plaintext, baOutput.toByteArray());
}
 
Example #24
Source File: CipherStreamClose.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #25
Source File: WrongAAD.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void decryptWithEmptyAAD() throws Exception {
    System.out.println("decryptWithEmptyAAD() started");
    // initialize it with empty AAD to get exception during decryption
    Cipher decryptCipher = createCipher(Cipher.DECRYPT_MODE,
            encryptCipher.getParameters());
    try (ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
                    decryptCipher)) {
        if (decrypt(ciOutput, baOutput)) {
            throw new RuntimeException(
                    "Decryption has been perfomed successfully in"
                            + " spite of the decrypt Cipher has NOT been"
                            + " initialized with AAD");
        }
    }
    System.out.println("decryptWithEmptyAAD() passed");
}
 
Example #26
Source File: CICO_PBE_RW_Test.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The CICO PBE RW test specific part of the super.doTest(). Implements the
 * scenario in accordance to the class description.
 * @param type byteArrayBuffering or intByteBuffering
 * @throws IOException  any I/O operation failed.
 * @throws GeneralSecurityException any security error.
 */
@Override
public void proceedTest(String type) throws IOException,
        GeneralSecurityException {
    ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
    try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
            getDecryptCipher())) {
        if (type.equals(CICO_PBE_Test.BYTE_ARR_BUFFER)) {
            proceedTestUsingByteArrayBuffer(ciOutput);
        } else {
            proceedTestUsingIntBuffer(ciOutput);
        }
        ciOutput.flush();
    }
    // Compare input and output
    if (!TestUtilities.equalsBlock(plainText, baOutput.toByteArray(), TEXT_SIZE)) {
        throw new RuntimeException("outputText not same with expectedText"
                + " when test " + type);
    }
}
 
Example #27
Source File: PFSecurityUtilsOld.java    From PFLockScreen-Android with Apache License 2.0 6 votes vote down vote up
private byte[] rsaEncrypt(
        @NonNull Context context,
        byte[] secret,
        String keystoreAlias
) throws Exception {
    final KeyStore keyStore = loadKeyStore();
    generateKeyIfNecessary(context, keyStore, keystoreAlias, false);
    final KeyStore.PrivateKeyEntry privateKeyEntry
            = (KeyStore.PrivateKeyEntry) keyStore.getEntry(keystoreAlias, null);
    final Cipher inputCipher = Cipher.getInstance(RSA_MODE, PROVIDER);
    inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final CipherOutputStream cipherOutputStream
            = new CipherOutputStream(outputStream, inputCipher);
    cipherOutputStream.write(secret);
    cipherOutputStream.close();
    final byte[] vals = outputStream.toByteArray();
    return vals;
}
 
Example #28
Source File: CICO_PBE_RW_Test.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The CICO PBE RW test specific part of the super.doTest(). Implements the
 * scenario in accordance to the class description.
 * @param type byteArrayBuffering or intByteBuffering
 * @throws IOException  any I/O operation failed.
 * @throws GeneralSecurityException any security error.
 */
@Override
public void proceedTest(String type) throws IOException,
        GeneralSecurityException {
    ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
    try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
            getDecryptCipher())) {
        if (type.equals(CICO_PBE_Test.BYTE_ARR_BUFFER)) {
            proceedTestUsingByteArrayBuffer(ciOutput);
        } else {
            proceedTestUsingIntBuffer(ciOutput);
        }
        ciOutput.flush();
    }
    // Compare input and output
    if (!TestUtilities.equalsBlock(plainText, baOutput.toByteArray(), TEXT_SIZE)) {
        throw new RuntimeException("outputText not same with expectedText"
                + " when test " + type);
    }
}
 
Example #29
Source File: CryptoHelper.java    From JPPF with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypt the specified string message to the specified output stream.
 * @param message the string to encrypt.
 * @param destination the stream into which the encrypted data is written.
 * @throws Exception if any error occurs while encrypting the data.
 */
static void encryptAndWrite(final String message, final OutputStream destination) throws Exception {
  // create a cipher instance
  final Cipher cipher = Cipher.getInstance(getTransformation());
  // init the cipher in encryption mode
  cipher.init(Cipher.ENCRYPT_MODE, getSecretKey());
  final ByteArrayOutputStream baos = new ByteArrayOutputStream();
  // obtain a cipher output stream
  try (final DataOutputStream cos = new DataOutputStream(new CipherOutputStream(baos, cipher))) {
    // finally, encrypt the message
    cos.writeUTF(message);
  }
  final DataOutputStream dos = new DataOutputStream(destination);
  final byte[] encrypted = baos.toByteArray();
  // write the length of the encrypted data
  dos.writeInt(encrypted.length);
  // write the encrypted data
  dos.write(encrypted);
  dos.flush();
}
 
Example #30
Source File: AndroidCryptoUtils.java    From zrtp-java with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public byte[] aesDecrypt(byte[] data, int offset, int length, byte[] key,
		byte[] initVector) throws CryptoException {
	try {
		SecretKeySpec scs = new SecretKeySpec(key, "AES");
		Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding", "ZBC");
		IvParameterSpec iv = new IvParameterSpec(initVector);
		ByteArrayOutputStream baos = new ByteArrayOutputStream(length);
		cipher.init(Cipher.DECRYPT_MODE, scs, iv);
		CipherOutputStream out = new CipherOutputStream(baos, cipher);
		out.write(data, offset, length);
		out.close();
		baos.close();
		return baos.toByteArray();
	} catch (Exception e) {
		throw new CryptoException(e);
	}
}