public static void readAndWriteData(InputStream inputStream, OutputStream outputStream) throws IOException {
BufferedSource source = Okio.buffer(Okio.source(inputStream));
BufferedSink sink = Okio.buffer(Okio.sink(outputStream));
while (!source.exhausted()) {
sink.writeAll(source);
}
sink.flush();
sink.close();
source.close();
}
public static void encryptData(File sourceFile, File outputEncryptedFile, byte[] key) throws IOException {
BufferedSource source = Okio.buffer(Okio.source(sourceFile));
BufferedSink sink = Okio.buffer(Okio.sink(outputEncryptedFile));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
while (!source.exhausted()) {
byte[] buffer = new byte[1024];
int bytesRead = source.read(buffer);
byte[] encryptedBytes = cipher.update(buffer, 0, bytesRead);
sink.write(encryptedBytes);
}
byte[] encryptedBytes = cipher.doFinal();
sink.write(encryptedBytes);
sink.flush();
sink.close();
source.close();
}
public static void decryptData(File encryptedFile, File outputDecryptedFile, byte[] key) throws IOException {
BufferedSource source = Okio.buffer(Okio.source(encryptedFile));
BufferedSink sink = Okio.buffer(Okio.sink(outputDecryptedFile));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
while (!source.exhausted()) {
byte[] buffer = new byte[1024];
int bytesRead = source.read(buffer);
byte[] decryptedBytes = cipher.update(buffer, 0, bytesRead);
sink.write(decryptedBytes);
}
byte[] decryptedBytes = cipher.doFinal();
sink.write(decryptedBytes);
sink.flush();
sink.close();
source.close();
}
public static String calculateCRC32(File file) throws IOException {
BufferedSource source = Okio.buffer(Okio.source(file));
CRC32 crc32 = new CRC32();
while (!source.exhausted()) {
crc32.update(source.readByteArray());
}
source.close();
return Long.toHexString(crc32.getValue());
}
public static String calculateSHA1(File file) throws IOException {
BufferedSource source = Okio.buffer(Okio.source(file));
MessageDigest digest = MessageDigest.getInstance("SHA-1");
while (!source.exhausted()) {
digest.update(source.readByteArray());
}
byte[] hashBytes = digest.digest();
StringBuilder hashHex = new StringBuilder();
for (byte hashByte : hashBytes) {
hashHex.append(Integer.toHexString(0xFF & hashByte));
}
source.close();
return hashHex.toString();
}