下面列出了怎么用javax.crypto.CipherOutputStream的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
/**
* 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);
}
}
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");
}
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");
}
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;
}
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;
}
@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);
}
}
@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());
}
/**
* 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);
}
}
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;
}
@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());
}
@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();
}
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;
}
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");
}
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;
}
/**
* 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);
}
}
/**
* 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();
}
@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);
}
}
/**
* 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);
}
}
@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());
}
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");
}
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");
}
@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());
}
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;
}
@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);
}
}
/**
* 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);
}
}
private void EncryptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EncryptActionPerformed
try{
FileInputStream file = new FileInputStream(file_path.getText());
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();
JOptionPane.showMessageDialog(null, "The file encrypted Successfully");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
// TODO add your handling code here:
}
private void DecryptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DecryptActionPerformed
try{
FileInputStream file = new FileInputStream("C:\\Users\\SMP\\Documents\\NetBeansProjects\\Rohan\\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();
JOptionPane.showMessageDialog(null, "The image was decrypted successfully");
Runtime.getRuntime().exec("rundll32 url.dll, FileProtocolHandler "+"Decrypt.jpg");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
// TODO add your handling code here:
}
/**
* <p>Wraps an <code>OutputStream</code> with a <code>CipherOutputStream</code> using this encryptor's cipher.</p>
* <p>If an <code>ivLength</code> has been specified or an explicit IV has been set during construction
* and <code>prependIV</code> is set to <code>true</code> this method will write an IV to the <code>OutputStream</code> before wrapping it.</p>
* @param os
* @return
* @throws GeneralSecurityException
* @throws IOException
*/
public CipherOutputStream wrapOutputStream(OutputStream os, byte[] iv) throws GeneralSecurityException, IOException {
Cipher cipher = getCipher(true);
if(iv == null && generateIV && ivLength > 0) {
iv = generateIV();
}
if(iv != null) {
cipher.init(Cipher.ENCRYPT_MODE, getKey(), getAlgorithmParameterSpec(iv));
} else {
cipher.init(Cipher.ENCRYPT_MODE, getKey());
iv = cipher.getIV();
}
ivThreadLocal.set(iv);
if(prependIV && iv != null) {
os.write(iv);
}
return new CipherOutputStream(os, cipher);
}
@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;
}