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

The following examples show how to use javax.crypto.CipherOutputStream#write() . 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: EncryptedCoder.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
OutputStream createEncryptedOutputStream(@NonNull byte[] masterKey, @NonNull File file)
    throws IOException
{
  try {
    byte[] random = Util.getSecretBytes(32);
    Mac    mac    = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(masterKey, "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));

    fileOutputStream.write(MAGIC_BYTES);
    fileOutputStream.write(random);

    CipherOutputStream outputStream = new CipherOutputStream(fileOutputStream, cipher);
    outputStream.write(MAGIC_BYTES);

    return outputStream;
  } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException e) {
    throw new AssertionError(e);
  }
}
 
Example 2
Source File: CICO_PBE_RW_Test.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Implements int buffering type test case.
 * @param ciOutput output stream for data written.
 * @throws java.io.IOException any I/O operation failed.
 */
public void proceedTestUsingIntBuffer(CipherOutputStream ciOutput)
        throws IOException {
    int buffer = getCiInput().read();
    while (buffer != -1) {
        ciOutput.write(buffer);
        buffer = getCiInput().read();
    }
}
 
Example 3
Source File: CipherHelper.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
void encryptData(WrapToken token, byte[] confounder, byte[] plaintext,
    int start, int len, byte[] padding, OutputStream os)
    throws GSSException, IOException {

    switch (sealAlg) {
    case MessageToken.SEAL_ALG_DES:
        // Encrypt on the fly and write
        Cipher des = getInitializedDes(true, getDesEncryptionKey(keybytes),
            ZERO_IV);
        CipherOutputStream cos = new CipherOutputStream(os, des);
        // debug(getHexBytes(confounder, confounder.length));
        cos.write(confounder);
        // debug(" " + getHexBytes(plaintext, start, len));
        cos.write(plaintext, start, len);
        // debug(" " + getHexBytes(padding, padding.length));
        cos.write(padding);
        break;

    case MessageToken.SEAL_ALG_DES3_KD:
        byte[] ctext = des3KdEncrypt(confounder, plaintext, start, len,
            padding);

        // Write to stream
        os.write(ctext);
        break;

    case MessageToken.SEAL_ALG_ARCFOUR_HMAC:
        byte[] ciphertext = arcFourEncrypt(token, confounder, plaintext,
            start, len, padding);

        // Write to stream
        os.write(ciphertext);
        break;

    default:
        throw new GSSException(GSSException.FAILURE, -1,
            "Unsupported seal algorithm: " + sealAlg);
    }
}
 
Example 4
Source File: CipherAgentImpl.java    From GDH with MIT License 5 votes vote down vote up
/**
 * Encrypt a value with a key and initial vector
 * 
 * @param value
 *            the String value to encrypt
 * @param iv
 *            the initial vector. Must be a random 128 bit value and the
 *            same one used in decryption
 * @param key
 *            the key for encryption
 * 
 * @return the encrypted bytes
 */
public byte[] encrypt(String value, byte[] iv, SecretKey key)
        throws InvalidKeyException, InvalidAlgorithmParameterException, IOException {
    byte[] encryptedBytes = null;
    IvParameterSpec ivspec = new IvParameterSpec(iv);
    encryptCipher.init(Cipher.ENCRYPT_MODE, key, ivspec);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptCipher);
    cipherOutputStream.write(value.getBytes(StandardCharsets.UTF_8));
    cipherOutputStream.flush();
    cipherOutputStream.close();
    encryptedBytes = outputStream.toByteArray();

    return encryptedBytes;
}
 
Example 5
Source File: CipherHelper.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
void encryptData(WrapToken token, byte[] confounder, byte[] plaintext,
    int start, int len, byte[] padding, OutputStream os)
    throws GSSException, IOException {

    switch (sealAlg) {
    case MessageToken.SEAL_ALG_DES:
        // Encrypt on the fly and write
        Cipher des = getInitializedDes(true, getDesEncryptionKey(keybytes),
            ZERO_IV);
        CipherOutputStream cos = new CipherOutputStream(os, des);
        // debug(getHexBytes(confounder, confounder.length));
        cos.write(confounder);
        // debug(" " + getHexBytes(plaintext, start, len));
        cos.write(plaintext, start, len);
        // debug(" " + getHexBytes(padding, padding.length));
        cos.write(padding);
        break;

    case MessageToken.SEAL_ALG_DES3_KD:
        byte[] ctext = des3KdEncrypt(confounder, plaintext, start, len,
            padding);

        // Write to stream
        os.write(ctext);
        break;

    case MessageToken.SEAL_ALG_ARCFOUR_HMAC:
        byte[] ciphertext = arcFourEncrypt(token, confounder, plaintext,
            start, len, padding);

        // Write to stream
        os.write(ciphertext);
        break;

    default:
        throw new GSSException(GSSException.FAILURE, -1,
            "Unsupported seal algorithm: " + sealAlg);
    }
}
 
Example 6
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 7
Source File: ReadWriteSkip.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void doIntTest(CipherOutputStream out) throws IOException {
    int buffer = ciInput.read();
    while (buffer != -1) {
        out.write(buffer);
        buffer = ciInput.read();
    }
}
 
Example 8
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 9
Source File: CipherHelper.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
void encryptData(WrapToken token, byte[] confounder, byte[] plaintext,
    int start, int len, byte[] padding, OutputStream os)
    throws GSSException, IOException {

    switch (sealAlg) {
    case MessageToken.SEAL_ALG_DES:
        // Encrypt on the fly and write
        Cipher des = getInitializedDes(true, getDesEncryptionKey(keybytes),
            ZERO_IV);
        CipherOutputStream cos = new CipherOutputStream(os, des);
        // debug(getHexBytes(confounder, confounder.length));
        cos.write(confounder);
        // debug(" " + getHexBytes(plaintext, start, len));
        cos.write(plaintext, start, len);
        // debug(" " + getHexBytes(padding, padding.length));
        cos.write(padding);
        break;

    case MessageToken.SEAL_ALG_DES3_KD:
        byte[] ctext = des3KdEncrypt(confounder, plaintext, start, len,
            padding);

        // Write to stream
        os.write(ctext);
        break;

    case MessageToken.SEAL_ALG_ARCFOUR_HMAC:
        byte[] ciphertext = arcFourEncrypt(token, confounder, plaintext,
            start, len, padding);

        // Write to stream
        os.write(ciphertext);
        break;

    default:
        throw new GSSException(GSSException.FAILURE, -1,
            "Unsupported seal algorithm: " + sealAlg);
    }
}
 
Example 10
Source File: ReadWriteSkip.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void doByteTest(CipherOutputStream out) throws IOException {
    byte[] buffer = Helper.generateBytes(textLength + 1);
    int len = ciInput.read(buffer);
    while (len != -1) {
        out.write(buffer, 0, len);
        len = ciInput.read(buffer);
    }
}
 
Example 11
Source File: CICO_PBE_RW_Test.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Implements byte array buffering type test case of the CICO PBE RW test.
 * @param ciOutput  output stream for data written.
 * @throws java.io.IOException any I/O operation failed.
 */
public void proceedTestUsingByteArrayBuffer(
        CipherOutputStream ciOutput) throws IOException {
    byte[] buffer = new byte[TEXT_SIZE];
    int len = getCiInput().read(buffer);
    while (len != -1) {
        ciOutput.write(buffer, 0, len);
        len = getCiInput().read(buffer);
    }
}
 
Example 12
Source File: CipherOutputStreamTest.java    From wycheproof with Apache License 2.0 5 votes vote down vote up
/**
 * Tests decryption of corrupted ciphertext. The test may accept empty plaintext as valid
 * result because of the problem with CipherOutputStream described in the header of this file.
 * @param tests an iterable with valid test vectors, that will be corrupted for the test
 * @param acceptEmptyPlaintext determines whether an empty plaintext instead of an exception
 *     is acceptable.
 */
@SuppressWarnings("InsecureCryptoUsage")
public void testCorruptDecrypt(Iterable<TestVector> tests, boolean acceptEmptyPlaintext)
    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);
    byte[] ct = Arrays.copyOf(t.ct, t.ct.length);
    ct[ct.length - 1] ^= (byte) 1;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    CipherOutputStream cos = new CipherOutputStream(os, cipher);
    cos.write(ct);
    try {
      // cos.close() should call cipher.doFinal().
      cos.close();
      byte[] decrypted = os.toByteArray();
      // Unfortunately Oracle thinks that returning an empty array is valid behaviour.
      // We accept empty results here, but flag them in the next test, so that we can distinguish
      // between beheviour considered acceptable by Oracle and more serious flaws.
      if (decrypted.length > 0) {
        fail(
            "this should fail; decrypted:"
                + TestUtil.bytesToHex(decrypted)
                + " pt: "
                + TestUtil.bytesToHex(t.pt));
      } else if (decrypted.length == 0 && !acceptEmptyPlaintext) {
        fail("Corrupted ciphertext returns empty plaintext");
      }
    } catch (IOException ex) {
      // expected
    }
  }
}
 
Example 13
Source File: ReadWriteSkip.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void doIntTest(CipherOutputStream out) throws IOException {
    int buffer = ciInput.read();
    while (buffer != -1) {
        out.write(buffer);
        buffer = ciInput.read();
    }
}
 
Example 14
Source File: IdSampleFragment.java    From genymotion-binocle with Apache License 2.0 5 votes vote down vote up
private void doEncode() {
    try {
        // Set up secret key spec for 128-bit AES encryption
        String androidId = Secure.getString(getActivity().getContentResolver(), Secure.ANDROID_ID);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(androidId.toCharArray(), salt, 45, 128);
        SecretKeySpec sks = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");

        // Create AES cipher
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, sks);

        // This stream write the encrypted text.
        FileOutputStream fos = getActivity().openFileOutput(FILE_NAME, Activity.MODE_PRIVATE);
        // Wrap the output stream
        CipherOutputStream cos = new CipherOutputStream(fos, cipher);

        // Write bytes
        cos.write(SECRET_MESSAGE.getBytes(UTF8_CHARSET));

        // Flush and close streams.
        cos.flush();
        cos.close();
        fos.close();

        tvAndroidId.setText(getActivity().getResources().getString(R.string.encoding_done, androidId));

    } catch (NoSuchPaddingException
            |NoSuchAlgorithmException
            |IOException
            |InvalidKeyException
            |InvalidKeySpecException e) {
        Log.e(TAG, "Unable to encrypt secret", e);
        tvAndroidId.setText(R.string.encoding_failed);
    }
}
 
Example 15
Source File: Encryption.java    From dtube-mobile-unofficial with Apache License 2.0 5 votes vote down vote up
void encryptString(String alias, String data) {
    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);

        createNewKeys(alias,keyStore);

        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);
        RSAPublicKey publicKey = (RSAPublicKey) privateKeyEntry.getCertificate().getPublicKey();

        Cipher input = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
        input.init(Cipher.ENCRYPT_MODE, publicKey);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(
                outputStream, input);
        cipherOutputStream.write(data.getBytes("UTF-8"));
        cipherOutputStream.close();

        byte [] vals = outputStream.toByteArray();
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(c);
        sharedPref.edit().putString("cypher", Base64.encodeToString(vals, Base64.DEFAULT)).apply();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Source File: CipherHelper.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void encryptData(WrapToken token, byte[] confounder, byte[] plaintext,
    int start, int len, byte[] padding, OutputStream os)
    throws GSSException, IOException {

    switch (sealAlg) {
    case MessageToken.SEAL_ALG_DES:
        // Encrypt on the fly and write
        Cipher des = getInitializedDes(true, getDesEncryptionKey(keybytes),
            ZERO_IV);
        CipherOutputStream cos = new CipherOutputStream(os, des);
        // debug(getHexBytes(confounder, confounder.length));
        cos.write(confounder);
        // debug(" " + getHexBytes(plaintext, start, len));
        cos.write(plaintext, start, len);
        // debug(" " + getHexBytes(padding, padding.length));
        cos.write(padding);
        break;

    case MessageToken.SEAL_ALG_DES3_KD:
        byte[] ctext = des3KdEncrypt(confounder, plaintext, start, len,
            padding);

        // Write to stream
        os.write(ctext);
        break;

    case MessageToken.SEAL_ALG_ARCFOUR_HMAC:
        byte[] ciphertext = arcFourEncrypt(token, confounder, plaintext,
            start, len, padding);

        // Write to stream
        os.write(ciphertext);
        break;

    default:
        throw new GSSException(GSSException.FAILURE, -1,
            "Unsupported seal algorithm: " + sealAlg);
    }
}
 
Example 17
Source File: CICO_PBE_RW_Test.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Implements int buffering type test case.
 * @param ciOutput output stream for data written.
 * @throws java.io.IOException any I/O operation failed.
 */
public void proceedTestUsingIntBuffer(CipherOutputStream ciOutput)
        throws IOException {
    int buffer = getCiInput().read();
    while (buffer != -1) {
        ciOutput.write(buffer);
        buffer = getCiInput().read();
    }
}
 
Example 18
Source File: CICO_PBE_RW_Test.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Implements byte array buffering type test case of the CICO PBE RW test.
 * @param ciOutput  output stream for data written.
 * @throws java.io.IOException any I/O operation failed.
 */
public void proceedTestUsingByteArrayBuffer(
        CipherOutputStream ciOutput) throws IOException {
    byte[] buffer = new byte[TEXT_SIZE];
    int len = getCiInput().read(buffer);
    while (len != -1) {
        ciOutput.write(buffer, 0, len);
        len = getCiInput().read(buffer);
    }
}
 
Example 19
Source File: CipherHelper.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
void encryptData(WrapToken token, byte[] confounder, byte[] plaintext,
    int start, int len, byte[] padding, OutputStream os)
    throws GSSException, IOException {

    switch (sealAlg) {
    case MessageToken.SEAL_ALG_DES:
        // Encrypt on the fly and write
        Cipher des = getInitializedDes(true, getDesEncryptionKey(keybytes),
            ZERO_IV);
        CipherOutputStream cos = new CipherOutputStream(os, des);
        // debug(getHexBytes(confounder, confounder.length));
        cos.write(confounder);
        // debug(" " + getHexBytes(plaintext, start, len));
        cos.write(plaintext, start, len);
        // debug(" " + getHexBytes(padding, padding.length));
        cos.write(padding);
        break;

    case MessageToken.SEAL_ALG_DES3_KD:
        byte[] ctext = des3KdEncrypt(confounder, plaintext, start, len,
            padding);

        // Write to stream
        os.write(ctext);
        break;

    case MessageToken.SEAL_ALG_ARCFOUR_HMAC:
        byte[] ciphertext = arcFourEncrypt(token, confounder, plaintext,
            start, len, padding);

        // Write to stream
        os.write(ciphertext);
        break;

    default:
        throw new GSSException(GSSException.FAILURE, -1,
            "Unsupported seal algorithm: " + sealAlg);
    }
}
 
Example 20
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
	}
}