Java Code Examples for javax.crypto.CipherOutputStream#close()

The following examples show how to use javax.crypto.CipherOutputStream#close() . 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: AesUtil.java    From littleca with Apache License 2.0 6 votes vote down vote up
public static void decryptInputStream(InputStream inputStream, String password, OutputStream out) throws Exception {
    try {
        Cipher cipher = AesHelper.getAesCipher(iv, password.getBytes(), Cipher.DECRYPT_MODE, CIPHER_MODE);
        CipherOutputStream cipherOutputStream = new CipherOutputStream(out, cipher);
        byte[] buf = new byte[BUFF_SIZE];
        int len = -1;
        while ((len = inputStream.read(buf)) != -1) {
            cipherOutputStream.write(buf, 0, len);
            cipherOutputStream.flush();
        }
        cipherOutputStream.close();
        out.close();
        inputStream.close();
    } catch (Exception e) {
        throw e;
    }
}
 
Example 2
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 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[] 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);
	}
}
 
Example 4
Source File: Cryptography.java    From zap-android with MIT License 6 votes vote down vote up
private byte[] rsaEncryptKey(byte[] secret) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, NoSuchProviderException, NoSuchPaddingException, UnrecoverableEntryException, InvalidKeyException {

        KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE_NAME);
        keyStore.load(null);

        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY_ENCRYPTION, null);
        Cipher inputCipher = Cipher.getInstance(RSA_MODE, CIPHER_PROVIDER_NAME_ENCRYPTION_DECRYPTION_RSA);
        inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inputCipher);
        cipherOutputStream.write(secret);
        cipherOutputStream.close();

        byte[] encryptedKeyAsByteArray = outputStream.toByteArray();
        return encryptedKeyAsByteArray;
    }
 
Example 5
Source File: CipherStorageAndroidKeystore.java    From keystore-ultimate with Apache License 2.0 6 votes vote down vote up
private static byte[] encryptString(Key key, String value) throws CryptoFailedException {
    try {
        Cipher cipher = Cipher.getInstance(ENCRYPTION_TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // write initialization vector to the beginning of the stream
        byte[] iv = cipher.getIV();
        outputStream.write(iv, 0, iv.length);
        // encrypt the value using a CipherOutputStream
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
        cipherOutputStream.write(value.getBytes(DEFAULT_CHARSET));
        cipherOutputStream.close();
        return outputStream.toByteArray();
    } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException e) {
        throw new CryptoFailedException("Could not encrypt value", e);
    }
}
 
Example 6
Source File: CipherStorageKeystoreAESCBC.java    From react-native-secure-storage with MIT License 6 votes vote down vote up
private byte[] encryptString(Key key, String service, String value) throws CryptoFailedException {
    try {
        Cipher cipher = Cipher.getInstance(ENCRYPTION_TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // write initialization vector to the beginning of the stream
        byte[] iv = cipher.getIV();
        outputStream.write(iv, 0, iv.length);
        // encrypt the value using a CipherOutputStream
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
        cipherOutputStream.write(value.getBytes(charsetName));
        cipherOutputStream.close();
        return outputStream.toByteArray();
    } catch (Exception e) {
        throw new CryptoFailedException("Could not encrypt value for service " + service, e);
    }
}
 
Example 7
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 8
Source File: RNSecureKeyStoreModule.java    From react-native-secure-key-store with ISC License 5 votes vote down vote up
private byte[] encryptCipherText(Cipher cipher, byte[] plainTextBytes) throws GeneralSecurityException, IOException {
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
  cipherOutputStream.write(plainTextBytes);
  cipherOutputStream.close();
  return outputStream.toByteArray();
}
 
Example 9
Source File: KeyGenHelper.java    From privacy-friendly-food-tracker with GNU General Public License v3.0 5 votes vote down vote up
private static byte[] rsaEncrypt(byte[] secret) throws Exception {
    KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
    keyStore.load(null);
    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY_ALIAS, null);
    // Encrypt the text
    Cipher inputCipher = Cipher.getInstance(RSA_MODE);
    inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inputCipher);
    cipherOutputStream.write(secret);
    cipherOutputStream.close();

    return outputStream.toByteArray();
}
 
Example 10
Source File: BcKeyStoreSpi.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public void engineStore(OutputStream stream, char[] password) 
    throws IOException
{
    Cipher              cipher;
    DataOutputStream    dOut = new DataOutputStream(stream);
    byte[]              salt = new byte[STORE_SALT_SIZE];
    int                 iterationCount = MIN_ITERATIONS + (random.nextInt() & 0x3ff);
    
    random.nextBytes(salt);
    
    dOut.writeInt(version);
    dOut.writeInt(salt.length);
    dOut.write(salt);
    dOut.writeInt(iterationCount);
    
    cipher = this.makePBECipher(STORE_CIPHER, Cipher.ENCRYPT_MODE, password, salt, iterationCount);
    
    CipherOutputStream  cOut = new CipherOutputStream(dOut, cipher);
    DigestOutputStream  dgOut = new DigestOutputStream(new SHA1Digest());
    
    this.saveStore(new TeeOutputStream(cOut, dgOut));
    
    byte[]  dig = dgOut.getDigest();

    cOut.write(dig);
    
    cOut.close();
}
 
Example 11
Source File: CryptHelper.java    From UpdogFarmer with GNU General Public License v3.0 5 votes vote down vote up
public static String encryptString(Context context, String toEncrypt) {
    if (TextUtils.isEmpty(toEncrypt)) {
        return "";
    }
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            final KeyStore.PrivateKeyEntry privateKeyEntry = getPrivateKey(context);
            if (privateKeyEntry != null) {
                final PublicKey publicKey = privateKeyEntry.getCertificate().getPublicKey();

                // Encrypt the text
                final Cipher input = Cipher.getInstance(CYPHER);
                input.init(Cipher.ENCRYPT_MODE, publicKey);

                final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                final CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, input);
                cipherOutputStream.write(toEncrypt.getBytes(Charset.forName(ENCODING)));
                cipherOutputStream.close();

                return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
            }
        } else {
            return Base64.encodeToString(toEncrypt.getBytes(Charset.forName(ENCODING)), Base64.DEFAULT);
        }
    } catch (Exception e) {
        Log.e(TAG, "Failed to encrypt string", e);
    }
    return "";
}
 
Example 12
Source File: FileStore.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
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();
    }
}
 
Example 13
Source File: BcKeyStoreSpi.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public void engineStore(OutputStream stream, char[] password) 
    throws IOException
{
    Cipher              cipher;
    DataOutputStream    dOut = new DataOutputStream(stream);
    byte[]              salt = new byte[STORE_SALT_SIZE];
    int                 iterationCount = MIN_ITERATIONS + (random.nextInt() & 0x3ff);
    
    random.nextBytes(salt);
    
    dOut.writeInt(version);
    dOut.writeInt(salt.length);
    dOut.write(salt);
    dOut.writeInt(iterationCount);
    
    cipher = this.makePBECipher(STORE_CIPHER, Cipher.ENCRYPT_MODE, password, salt, iterationCount);
    
    CipherOutputStream  cOut = new CipherOutputStream(dOut, cipher);
    DigestOutputStream  dgOut = new DigestOutputStream(new SHA1Digest());
    
    this.saveStore(new TeeOutputStream(cOut, dgOut));
    
    byte[]  dig = dgOut.getDigest();

    cOut.write(dig);
    
    cOut.close();
}
 
Example 14
Source File: RsaHelper.java    From android-showcase-template with Apache License 2.0 5 votes vote down vote up
/**
 * Perform encryption using RSA
 * @param mode the RSA encryption alg
 * @param keyEntry the private/public key entry
 * @param text the data to encrypt
 * @return the encrypted ddata
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static byte[] encrypt(String mode, KeyStore.PrivateKeyEntry keyEntry, byte[] text) throws GeneralSecurityException, IOException {
    // Encrypt the text
    Cipher inputCipher = Cipher.getInstance(mode);
    inputCipher.init(Cipher.ENCRYPT_MODE, keyEntry.getCertificate().getPublicKey());
    //The key to encrypt should be either 16 (128 bit) or 32 (256 bit) in size, well below the block size for RSA (should be around 214 bytes)
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inputCipher);
    cipherOutputStream.write(text);
    cipherOutputStream.close();

    byte[] vals = outputStream.toByteArray();
    return vals;
}
 
Example 15
Source File: CipherOutputStreamTest.java    From wycheproof with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("InsecureCryptoUsage")
public void testDecrypt(Iterable<TestVector> tests) throws Exception {
  for (TestVector t : tests) {
    Cipher cipher = Cipher.getInstance(t.algorithm);
    cipher.init(Cipher.DECRYPT_MODE, t.key, t.params);
    cipher.updateAAD(t.aad);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    CipherOutputStream cos = new CipherOutputStream(os, cipher);
    cos.write(t.ct);
    cos.close();
    assertEquals(TestUtil.bytesToHex(t.pt), TestUtil.bytesToHex(os.toByteArray()));
  }
}
 
Example 16
Source File: CryptUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private static void rsaEncrypt(Context context, BufferedInputStream inputStream, BufferedOutputStream outputStream)
        throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException,
        CertificateException, BadPaddingException, InvalidAlgorithmParameterException,
        KeyStoreException, UnrecoverableEntryException, IllegalBlockSizeException,
        InvalidKeyException, IOException {

    Cipher cipher = Cipher.getInstance(ALGO_AES, "BC");
    RSAKeygen keygen = new RSAKeygen(context);

    IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
    cipher.init(Cipher.ENCRYPT_MODE, keygen.getSecretKey(), ivParameterSpec);

    byte[] buffer = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
    int count;

    CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
    try {

        while ((count = inputStream.read(buffer)) != -1) {

            cipherOutputStream.write(buffer, 0, count);
            ServiceWatcherUtil.POSITION+=count;
        }
    } finally {

        cipherOutputStream.flush();
        cipherOutputStream.close();
        inputStream.close();
    }
}
 
Example 17
Source File: KeyStoreUtils.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private byte[] rsaEncrypt(byte[] secret) throws NoSuchAlgorithmException, UnrecoverableEntryException,
        KeyStoreException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException {
    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY_ALIAS, null);
    // Encrypt the text
    Cipher inputCipher = Cipher.getInstance(RSA_MODE, "AndroidOpenSSL");
    inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inputCipher);
    cipherOutputStream.write(secret);
    cipherOutputStream.close();

    byte[] vals = outputStream.toByteArray();
    return vals;
}
 
Example 18
Source File: ImgCry2.java    From Web-Based-Graphical-Password-Authentication-System with MIT License 4 votes vote down vote up
@Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
     // Set the MIME type for the response message
     response.setContentType("text/html");
     // Get a output writer to write the response message into the network socket
     PrintWriter out = response.getWriter();
  
  
  
  
  String a = request.getParameter("img");
  String b = "C:\\Users\\SMP\\Desktop\\Sky.jpg";
  try {
        out.println("<html>");
        out.println("<head><title>Image Decryption</title></head>");
        out.println("<body>");
        out.println("<h1>Image Decryption</h1>");
        // Generate a random number upon each request
        out.println("<p>Random Number: <strong>" + Math.random() + "</strong></p>");    
        

  
  
	  try{
           FileInputStream file = new FileInputStream("C:\\Users\\SMP\\Documents\\apache-tomcat-7.0.81\\bin\\Encrypt.jpg");
           FileOutputStream outStream = new FileOutputStream("Decrypt.jpg");
           byte k[]="CooL2116NiTh5252".getBytes();
           SecretKeySpec key = new SecretKeySpec(k, "AES");
           Cipher enc = Cipher.getInstance("AES");
           enc.init(Cipher.DECRYPT_MODE, key);
           CipherOutputStream cos = new CipherOutputStream(outStream, enc);
           byte[] buf = new byte[1024];
           int read;
           while((read=file.read(buf))!=-1){
               cos.write(buf,0,read);
           }
           file.close();
           outStream.flush();
           cos.close();
           out.println("The image was decrypted successfully");
           Runtime.getRuntime().exec("rundll32 url.dll, FileProtocolHandler "+"Decrypt.jpg");
       }catch(Exception e){
           out.println(""+ e);
       }
		out.println("</body></html>");
	}finally {
        out.close();  // Always close the output writer
	}
}
 
Example 19
Source File: ImgCry1.java    From Web-Based-Graphical-Password-Authentication-System with MIT License 4 votes vote down vote up
@Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
     // Set the MIME type for the response message
     response.setContentType("text/html");
     // Get a output writer to write the response message into the network socket
     PrintWriter out = response.getWriter();
  
  
  
  
  String a = request.getParameter("img");
  String b = "C:\\Users\\SMP\\Desktop\\" + a;
  try {
        out.println("<html>");
        out.println("<head><title>Image Encryption</title></head>");
        out.println("<body>");
        out.println("<h1>Image Encryption</h1>");
        // Echo client's request information
        out.println("<p>Request URL: " + a + "</p>");
        // Generate a random number upon each request
        out.println("<p>Random Number: <strong>" + Math.random() + "</strong></p>");    

  
  
	  try{
			FileInputStream file = new FileInputStream(b);
			FileOutputStream outStream = new FileOutputStream("Encrypt.jpg");
			byte k[]="CooL2116NiTh5252".getBytes();
			SecretKeySpec key = new SecretKeySpec(k, "AES");
			Cipher enc = Cipher.getInstance("AES");
			enc.init(Cipher.ENCRYPT_MODE, key);
			CipherOutputStream cos = new CipherOutputStream(outStream, enc);
			byte[] buf = new byte[1024];
			int read;
			while((read=file.read(buf))!=-1){
				cos.write(buf,0,read);
			}
			file.close();
			outStream.flush();
			cos.close();
			out.println("The file encrypted successfully in bin folder");
			out.println("<form method='get' action='http://localhost:9999/password/imgcry2'><br><input type='submit' value='Decrypt'></form>");
		}catch(Exception e){
			out.println(""+ e);
		}
		out.println("</body></html>");
	}finally {
        out.close();  // Always close the output writer
	}
}
 
Example 20
Source File: AESCrypto.java    From weMessage with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Generates a random IV and encrypts bytes from a file with the given key. Then it is bundled in a
 * CipherByteArrayIv class.
 *
 * @param inputFile The file that will be encrypted
 * @param secretKeys The combined AES & HMAC keys with which to encrypt
 * @return a tuple of the IV and byte array
 * @throws GeneralSecurityException if AES is not implemented on this system
 * @throws IOException if the file is not found or an error occurs while reading bytes from it
 */

public static CipherByteArrayIv encryptFile(File inputFile, SecretKeys secretKeys) throws GeneralSecurityException, IOException {
    byte[] iv = generateIv();
    Cipher aesCipherForEncryption = Cipher.getInstance(CIPHER_TRANSFORMATION);
    aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKeys.getConfidentialityKey(), new IvParameterSpec(iv));

    iv = aesCipherForEncryption.getIV();

    BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(inputFile));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(baos, aesCipherForEncryption);

    int read;
    byte[] buffer = new byte[1024];
    boolean outOfMemTrigger = false;
    long fileLength = inputFile.length();

    while ((read = inputStream.read(buffer)) != -1) {
        if (checkMemoryAvailability.get()) {
            Runtime runtime = Runtime.getRuntime();
            long usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
            long maxHeapSize = runtime.maxMemory() / 1048576L;
            long availableHeapSize = maxHeapSize - usedMemory;

            if ((fileLength / 1048576L) > (availableHeapSize - 10)) {
                outOfMemTrigger = true;
                break;
            }
        }

        cipherOutputStream.write(buffer, 0, read);
    }

    baos.close();
    inputStream.close();
    cipherOutputStream.close();

    if (outOfMemTrigger){
        System.gc();
        return new OOMCipherByteArray();
    }

    return new CipherByteArrayIv(baos.toByteArray(), iv);
}