com.github.isaichkindanila.crypt.lib.stream.CryptStream Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of crypt-lib Show documentation
Show all versions of crypt-lib Show documentation
Simple Java library for stream ciphers based encryption
The newest version!
package com.github.isaichkindanila.crypt.lib.stream;
import com.github.isaichkindanila.crypt.lib.cipher.StandardStreamCipher;
import com.github.isaichkindanila.crypt.lib.cipher.StreamCipher;
import com.github.isaichkindanila.crypt.lib.util.EncryptionChecker;
import com.github.isaichkindanila.crypt.lib.util.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
class CryptStream {
static final int BUFFER_SIZE = 8192;
static final byte[] STREAM_SIGNATURE = EncryptionChecker.getEncryptionSignature();
private final MessageDigest sha256;
private final InputStream in;
private final OutputStream out;
CryptStream(InputStream in, OutputStream out) {
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("according to Oracle documentation, every implementation of the Java platform is required to support SHA-256 algorithm", e);
}
this.in = in;
this.out = out;
}
void writeStreamSignature() throws IOException {
out.write(STREAM_SIGNATURE);
}
void checkStreamSignature() throws IOException {
byte[] bytes = new byte[STREAM_SIGNATURE.length];
if (in.read(bytes) != bytes.length) {
throw new MalformedStreamHeaderException();
}
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] != STREAM_SIGNATURE[i]) {
throw new MalformedStreamHeaderException();
}
}
}
byte[] writeIV() throws IOException {
byte[] iv = new byte[StreamCipher.IV_LENGTH];
new SecureRandom().nextBytes(iv);
out.write(iv);
return iv;
}
byte[] readIV() throws IOException {
byte[] iv = new byte[StreamCipher.IV_LENGTH];
if (in.read(iv) != iv.length) {
throw new MalformedStreamHeaderException();
}
return iv;
}
byte[] hash(String password) {
return sha256.digest(password.getBytes(StandardCharsets.UTF_8));
}
byte[] hash(byte[] key, byte[] iv) {
sha256.update(key);
sha256.update(iv);
return sha256.digest();
}
void writeCipher(StandardStreamCipher cipher) throws IOException {
IOUtils.writeInt(cipher.ordinal(), out);
}
StandardStreamCipher readCipher() throws IOException {
int index = IOUtils.readInt(in);
StandardStreamCipher[] ciphers = StandardStreamCipher.values();
if (index < ciphers.length) {
return ciphers[index];
} else {
throw new UnsupportedCipherException(index);
}
}
}