當前位置: 首頁>>代碼示例>>Java>>正文


Java CipherOutputStream.flush方法代碼示例

本文整理匯總了Java中javax.crypto.CipherOutputStream.flush方法的典型用法代碼示例。如果您正苦於以下問題:Java CipherOutputStream.flush方法的具體用法?Java CipherOutputStream.flush怎麽用?Java CipherOutputStream.flush使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.crypto.CipherOutputStream的用法示例。


在下文中一共展示了CipherOutputStream.flush方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testCipherOutputStream

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
/**
 * CipherOutputStream(OutputStream os) method testing. Tests that
 * CipherOutputStream uses NullCipher if Cipher is not specified
 * in the constructor.
 */
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "",
    method = "CipherOutputStream",
    args = {java.io.OutputStream.class}
)
public void testCipherOutputStream() throws Exception {
    byte[] data = new byte[] { -127, -100, -50, -10, -1, 0, 1, 10, 50, 127 };
    TestOutputStream tos = new TestOutputStream();
    CipherOutputStream cos = new CipherOutputStream(tos){};
    cos.write(data);
    cos.flush();
    byte[] result = tos.toByteArray();
    if (!Arrays.equals(result, data)) {
        fail("NullCipher should be used " + "if Cipher is not specified.");
    }
}
 
開發者ID:keplersj,項目名稱:In-the-Box-Fork,代碼行數:23,代碼來源:CipherOutputStream1Test.java

示例2: testWrite1

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
/**
 * write(int b) method testing. Tests that method writes correct values to
 * the underlying output stream.
 */
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "Can not check IOException.",
    method = "write",
    args = {int.class}
)
public void testWrite1() throws Exception {
    byte[] data = new byte[] { -127, -100, -50, -10, -1, 0, 1, 10, 50, 127 };
    TestOutputStream tos = new TestOutputStream();
    CipherOutputStream cos = new CipherOutputStream(tos, new NullCipher());
    for (int i = 0; i < data.length; i++) {
        cos.write(data[i]);
    }
    cos.flush();
    byte[] result = tos.toByteArray();
    if (!Arrays.equals(result, data)) {
        fail("CipherOutputStream wrote incorrect data.");
    }
}
 
開發者ID:keplersj,項目名稱:In-the-Box-Fork,代碼行數:24,代碼來源:CipherOutputStream1Test.java

示例3: testWrite2

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
/**
 * write(byte[] b) method testing. Tests that method writes correct values
 * to the underlying output stream.
 */
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "Can not check IOException.",
    method = "write",
    args = {byte[].class}
)
public void testWrite2() throws Exception {
    byte[] data = new byte[] { -127, -100, -50, -10, -1, 0, 1, 10, 50, 127 };
    TestOutputStream tos = new TestOutputStream();
    CipherOutputStream cos = new CipherOutputStream(tos, new NullCipher());
    cos.write(data);
    cos.flush();
    byte[] result = tos.toByteArray();
    if (!Arrays.equals(result, data)) {
        fail("CipherOutputStream wrote incorrect data.");
    }

    try {
        cos.write(null);
        fail("NullPointerException expected");
    } catch (NullPointerException e) {
        //expected
    }
}
 
開發者ID:keplersj,項目名稱:In-the-Box-Fork,代碼行數:29,代碼來源:CipherOutputStream1Test.java

示例4: testWrite3

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
/**
 * write(byte[] b, int off, int len) method testing.
 */
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "Can not check IOException.",
    method = "write",
    args = {byte[].class, int.class, int.class}
)
public void testWrite3() throws Exception {
    byte[] data = new byte[] { -127, -100, -50, -10, -1, 0, 1, 10, 50, 127 };
    TestOutputStream tos = new TestOutputStream();
    CipherOutputStream cos = new CipherOutputStream(tos, new NullCipher());
    for (int i = 0; i < data.length; i++) {
        cos.write(data, i, 1);
    }
    cos.flush();
    byte[] result = tos.toByteArray();
    if (!Arrays.equals(result, data)) {
        fail("CipherOutputStream wrote incorrect data.");
    }
}
 
開發者ID:keplersj,項目名稱:In-the-Box-Fork,代碼行數:23,代碼來源:CipherOutputStream1Test.java

示例5: testFlush

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
/**
 * flush() method testing. Tests that method flushes the data to the
 * underlying output stream.
 */
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "Can not check IOException.",
    method = "flush",
    args = {}
)
public void testFlush() throws Exception {
    byte[] data = new byte[] { -127, -100, -50, -10, -1, 0, 1, 10, 50, 127 };
    TestOutputStream tos = new TestOutputStream();
    CipherOutputStream cos = new CipherOutputStream(tos){};
    cos.write(data);
    cos.flush();
    byte[] result = tos.toByteArray();
    if (!Arrays.equals(result, data)) {
        fail("CipherOutputStream did not flush the data.");
    }
}
 
開發者ID:keplersj,項目名稱:In-the-Box-Fork,代碼行數:22,代碼來源:CipherOutputStream1Test.java

示例6: decrypt

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
private boolean decrypt(CipherOutputStream ciOutput,
        ByteArrayOutputStream baOutput) throws IOException {
    try (ByteArrayInputStream baInput = new ByteArrayInputStream(plainText);
            CipherInputStream ciInput = new CipherInputStream(baInput,
                    encryptCipher)) {
        byte[] buffer = new byte[TEXT_SIZE];
        int len = ciInput.read(buffer);

        while (len != -1) {
            ciOutput.write(buffer, 0, len);
            len = ciInput.read(buffer);
        }
        ciOutput.flush();
        byte[] recoveredText = baOutput.toByteArray();
        System.out.println("recoveredText: " + new String(recoveredText));

        /*
         * See bug 8012900, AEADBadTagException is swalloed by CI/CO streams
         * If recovered text is empty, than decryption failed
         */
        if (recoveredText.length == 0) {
            return false;
        }
        return Arrays.equals(plainText, recoveredText);
    } catch (IllegalStateException e) {
        System.out.println("Expected IllegalStateException: "
                + e.getMessage());
        e.printStackTrace(System.out);
        return false;
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:32,代碼來源:WrongAAD.java

示例7: encrypt

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:maxamel,項目名稱:GDH,代碼行數:28,代碼來源:CipherAgentImpl.java

示例8: encryptSymmetricKey

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
public static byte[] encryptSymmetricKey(byte[] symKey, PublicKey pKey)
		throws SymmetricKeyEncryptionException {
	try {
		ASYMM_CIPHER.init(Cipher.ENCRYPT_MODE, pKey);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		CipherOutputStream cos = new CipherOutputStream(bos, ASYMM_CIPHER);
		cos.write(symKey);
		cos.flush();
		cos.close();
		byte[] byteArray = bos.toByteArray();
		return byteArray;
	} catch (Exception e) {
		throw new SymmetricKeyEncryptionException(e);
	}
}
 
開發者ID:Rohde-Schwarz-Cybersecurity,項目名稱:PanBox,代碼行數:16,代碼來源:CryptCore.java

示例9: _asymmetricDecrypt

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
public static byte[] _asymmetricDecrypt(byte[] symKey, PrivateKey pKey)
		throws InvalidKeyException, IOException {
	ASYMM_CIPHER.init(Cipher.DECRYPT_MODE, pKey);
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	CipherOutputStream cos = new CipherOutputStream(bos, ASYMM_CIPHER);
	cos.write(symKey);
	cos.flush();
	cos.close();
	byte[] byteArray = bos.toByteArray();
	return byteArray;
}
 
開發者ID:Rohde-Schwarz-Cybersecurity,項目名稱:PanBox,代碼行數:12,代碼來源:CryptCore.java

示例10: aesEncrypt

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
/**
 * Helper method to encrypt a file
 * @param inputStream stream associated with the file to be encrypted
 * @param outputStream stream associated with new output encrypted file
 */
@RequiresApi(api = Build.VERSION_CODES.M)
private static void aesEncrypt(BufferedInputStream inputStream, BufferedOutputStream outputStream)
        throws GeneralSecurityException, IOException {

    Cipher cipher = Cipher.getInstance(ALGO_AES);

    GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, IV.getBytes());

    cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(), gcmParameterSpec);

    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();
    }
}
 
開發者ID:TeamAmaze,項目名稱:AmazeFileManager,代碼行數:35,代碼來源:CryptUtil.java

示例11: rsaEncrypt

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private static void rsaEncrypt(Context context, BufferedInputStream inputStream, BufferedOutputStream outputStream)
        throws GeneralSecurityException, 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();
    }
}
 
開發者ID:TeamAmaze,項目名稱:AmazeFileManager,代碼行數:29,代碼來源:CryptUtil.java

示例12: doEncode

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
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);
    }
}
 
開發者ID:Genymobile,項目名稱:genymotion-binocle,代碼行數:37,代碼來源:IdSampleFragment.java

示例13: test1

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
private boolean test1(Cipher c, Cipher d, String s) throws Exception {
    start = System.nanoTime();
    File file = new File("slask.tmp");
    if (file.exists())
        file.delete();
    byte[] b = s.getBytes();

    FileOutputStream fos = new FileOutputStream(file);
    CipherOutputStream cos = new CipherOutputStream(fos, c);

    cos.write(b);
    cos.flush();
    cos.close();
    fos.close();

    FileInputStream fis = new FileInputStream(file);
    CipherInputStream cis = new CipherInputStream(fis, d);

    byte[] rb = new byte[1024];
    StringBuffer sb = new StringBuffer();
    int i, a = 0;
    while ((i = cis.read(rb)) != -1) {
        sb.append(new String(rb, 0, i));
        a += i;
    }
    cis.close();
    fis.close();
    file.delete();
    finish = System.nanoTime();
    return sb.toString().equals(s);
}
 
開發者ID:freeVM,項目名稱:freeVM,代碼行數:32,代碼來源:TestCipherStream.java

示例14: runTest

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
private void runTest(
    String  name)
    throws Exception
{
    String lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789";
    KeyGenerator            kGen;

    if (name.indexOf('/') < 0)
    {
        kGen = KeyGenerator.getInstance(name, "BC");
    }
    else
    {
        kGen = KeyGenerator.getInstance(name.substring(0, name.indexOf('/')), "BC");
    }

    Cipher                  in = Cipher.getInstance(name, "BC");
    Cipher                  out = Cipher.getInstance(name, "BC");
    Key                     key = kGen.generateKey();
    ByteArrayInputStream    bIn = new ByteArrayInputStream(lCode.getBytes());
    ByteArrayOutputStream   bOut = new ByteArrayOutputStream();

    in.init(Cipher.ENCRYPT_MODE, key);
    if (in.getIV() != null)
    {
        out.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(in.getIV()));
    }
    else
    {
        out.init(Cipher.DECRYPT_MODE, key);
    }

    CipherInputStream       cIn = new CipherInputStream(bIn, in);
    CipherOutputStream      cOut = new CipherOutputStream(bOut, out);

    int c;

    while ((c = cIn.read()) >= 0)
    {
        cOut.write(c);
    }

    cIn.close();

    cOut.flush();
    cOut.close();

    String  res = new String(bOut.toByteArray());

    if (!res.equals(lCode))
    {
        fail("Failed - decrypted data doesn't match.");
    }
}
 
開發者ID:NoYouShutup,項目名稱:CryptMeme,代碼行數:55,代碼來源:CipherStreamTest.java

示例15: encryptStreamIfUnderThreshold

import javax.crypto.CipherOutputStream; //導入方法依賴的package包/類
/**
 * Encrypts an input stream up to a given length.
 * Exits early if the encrypted data is longer than the abandon length.
 * 
 * @param sourceStream
 *            A <code>InputStream</code> object that represents the stream to measure.
 * @param targetStream
 *            A <code>ByteArrayOutputStream</code> object that represents the stream to write the encrypted data.
 * @param cipher
 *            The <code>Cipher</code> to use to encrypt the data. 
 * @param writeLength
 *            The number of bytes to read and encrypt from the sourceStream.
 * @param abandonLength
 *            The number of bytes to read before the analysis is abandoned. Set this value to <code>-1</code> to
 *            force the entire stream to be read. This parameter is provided to support upload thresholds.
 * @return
 *            The size of the encrypted stream, or -1 if the encrypted stream would be over the abandonLength.
 * @throws IOException
 *            If an I/O error occurs.
 */
public static long encryptStreamIfUnderThreshold(final InputStream sourceStream, final ByteArrayOutputStream targetStream, Cipher cipher, long writeLength,
        long abandonLength) throws IOException {
    if (abandonLength < 0) {
        abandonLength = Long.MAX_VALUE;
    }

    if (!sourceStream.markSupported()) {
        throw new IllegalArgumentException(SR.INPUT_STREAM_SHOULD_BE_MARKABLE);
    }

    sourceStream.mark(Constants.MAX_MARK_LENGTH);

    if (writeLength < 0) {
        writeLength = Long.MAX_VALUE;
    }
    
    CipherOutputStream encryptStream = new CipherOutputStream(targetStream, cipher);
    
    int count = -1;
    long totalEncryptedLength = targetStream.size();
    final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH];

    int nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength);
    count = sourceStream.read(retrievedBuff, 0, nextCopy);
    
    while (nextCopy > 0 && count != -1) {
        
        // Note: We are flushing the CryptoStream on every write here.  This way, we don't end up encrypting more data than we intend here, if
        // we go over the abandonLength.
        encryptStream.write(retrievedBuff, 0, count);
        encryptStream.flush();
        totalEncryptedLength = targetStream.size();

        if (totalEncryptedLength > abandonLength) {
            // Abandon operation
            break;
        }

        nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength);
        count = sourceStream.read(retrievedBuff, 0, nextCopy);
    }

    sourceStream.reset();
    sourceStream.mark(Constants.MAX_MARK_LENGTH);
    
    encryptStream.close();
    totalEncryptedLength = targetStream.size();
    if (totalEncryptedLength > abandonLength) {
        totalEncryptedLength = -1;
    }

    return totalEncryptedLength;
}
 
開發者ID:Azure,項目名稱:azure-storage-java,代碼行數:74,代碼來源:Utility.java


注:本文中的javax.crypto.CipherOutputStream.flush方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。