本文整理汇总了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.");
}
}
示例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.");
}
}
示例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
}
}
示例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.");
}
}
示例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.");
}
}
示例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;
}
}
示例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;
}
示例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);
}
}
示例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;
}
示例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();
}
}
示例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();
}
}
示例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);
}
}
示例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);
}
示例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.");
}
}
示例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;
}