Detecting incorrect key using AES/GCM in JAVA - java

I'm using AES to encrypt/decrypt some files in GCM mode using BouncyCastle.
While I'm proving wrong key for decryption there is no exception.
How should I check that the key is incorrect?
my code is this:
SecretKeySpec incorrectKey = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
byte[] block = new byte[1048576];
int i;
cipher.init(Cipher.DECRYPT_MODE, incorrectKey, ivSpec);
BufferedInputStream fis=new BufferedInputStream(new ProgressMonitorInputStream(null,"Decrypting ...",new FileInputStream("file.enc")));
BufferedOutputStream ro=new BufferedOutputStream(new FileOutputStream("file_org"));
CipherOutputStream dcOut = new CipherOutputStream(ro, cipher);
while ((i = fis.read(block)) != -1) {
dcOut.write(block, 0, i);
}
dcOut.close();
fis.close();
thanks

There is no method that you can detect incorrect key in GCM mode. What you can check is if the authentication tag validates, which means you were using the right key. The problem is that if the authentication tag is incorrect then this could indicate each of the following (or a combination of all, up to and including the full replacement of the ciphertext and authentication tag):
an incorrect key is being used;
the counter mode encrypted data was altered during transport;
the additional authenticated data was altered;
the authentication tag itself was altered during transport.
What you could do is send additional data to identify the secret key used. This could be a readable identifier ("encryption-key-1") but it could also be a KCV, a key check value. A KCV normally consists of a zero-block encrypted with the key, or a cryptographically secure hash over the key (also called a fingerprint). Because the encryption over a zero block leaks information you should not use that to identify the encryption key.
You could actually use the AAD feature of GCM mode to calculate the authentication tag over the key identification data. Note that you cannot distinguish between compromise of the fingerprint and using an incorrect key. It's however less likely that the fingerprint is accidentally damaged than the entire structure of IV, AAD, ciphertext and authentication tag.

You are using NoPadding. Change this to PKCS7Padding for both encryption and decryption. If the wrong key is used then the padding will almost certainly fail to decrypt as expected and an InvalidCipherTextException will be thrown.

Related

How to store a SecretKey within a Java KeyStore protected by a PublicKey (RSAPasswordProtection)?

I want to store a SecretKey within a Java KeyStore protected by a PublicKey. When loading the protected KeyEntry i would like to
get the protected key byte-array to manually unwrap it later on with a PrivateKey.
let the KeyStore handle the unwrapping when handing over the PrivateKey.
Using the setEntry()-Method with an already wrapped byte-Array is possible. Also getting the wrapped byte-Array back can be done by using the getEntry()-Method. To encrypt a SecretKey the setEntry()-Method supports the usage of a ProtectionParameter. The only ProtectionParameter i could find was the PasswordProtection parameter.
Does anyone know about a RsaProtection for Java KeyStore? Or is there another way around to be able to wrap SecretKeys using a PublicKey and getting it back using a PrivateKey?
The Java key stores are certainly not able to handle this; they primarily use symmetric encryption to protect the key stores. It is possible to wrap and unwrap keys though. I've shown this using OAEP instead of the less safe "RSA" (PKCS#1) encryption:
Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
rsa.init(Cipher.WRAP_MODE, keyPair.getPublic());
byte[] wrapped = rsa.wrap(aesKey);
rsa.init(Cipher.UNWRAP_MODE, keyPair.getPrivate());
SecretKey unwrappedAESKey = (SecretKey) rsa.unwrap(wrapped, "RSA", Cipher.SECRET_KEY);

Java's 3DES encryption generates trash at the end of encrypted data

I have a 3des Cipher object that is initialized like this:
KeySpec keySpec= new DESedeKeySpec(bytesKey);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey secretKey= secretKeyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(modo, secretKey);
When this object is used to encrypt data, no exception is thrown and the algorithm ends succesfully:
String unencryptedText = "192 character length text in clear.... ";
byte[] bytesUnencryptedText = unencryptedText.getBytes("UTF8");
byte[] bytesEncryptedData = cipher.doFinal(bytesUnencryptedText);
When we took a look at the encrypted data generated by the doFinal, we noticed 200 bytes are being returned, as opposed to 192 as we expected. These additional 8 bytes took the following hexa value: 08.
The first 192 bytes are correct and we already have been able to decrypt them and obtain our original data. But the additional 8 bytes are generating an error at our HSM.
How can we prevent the Cipher to inject these additional bytes?
The block size of DES is 64-bit or 8 bytes. When the plaintext size is a multiple of the plaintext the padding used will add another block of data to the plaintext filled with 0x08. This is how PKCS#5/PKCS#7 padding works.
It seems that your HSM expects that no padding is used. Also, from the comments it is apparent that "DESede" defaults to ECB mode, so the fully qualified Cipher would be:
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
Note that ECB mode is not semantically secure. If possible, use a different mode like CBC with an HMAC over the ciphertext, or simply an authenticated mode like GCM.
When you use NoPadding, the plaintext is filled up with 0x00 bytes and you will have to trim the decrypted plaintext yourself by removing all 0x00 bytes at the end. To do this, make sure that the plaintext doesn't actually contain 0x00 bytes at the end, otherwise you will remove actual plaintext bytes.

Java or Spring: two-way encryption with salt?

I am doing a web project with Spring.
I am hoping to do a two-way encryption (and decryption) of a few url parameters. I don't need very strong encryption.
I googled but found many are related to one-way password encryption, which is not what wanted.
Can any expert out there point me to the right place?
Thanks!
I can recommend really nice library called bouncy castle. On their homepage is a few nice examples. See https://www.bouncycastle.org/java.html
Another possibility is java crypto api and something like
SecretKey keySpec = new SecretKeySpec(keyBytes, "AES");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher aesCbc = Cipher.getInstance("AES/CBC/NoPadding");
aesCbc.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encryptedBytes = aesCbc.doFinal(plainTextBytes);
return Base64.encodeBase64String(encryptedBytes);
You can you use classes from javax.crypto to perform encryption and decryption.

Configure Jasypt Encryptors using my own SecretKey, instead of setting String password using the 'setPassword' method of the PBEString encryptors?

I'm trying to configure Jasypt StandardPBEStringEncryptor using the following code.
StandardPBEStringEncryptor strongEncryptor = new StandardPBEStringEncryptor();
strongEncryptor.setAlgorithm(ALGORITHM);
strongEncryptor.setPassword(PASSWORD);
And then call the encrypt() and decrypt() methods of the 'strongEncryptor' to perform the encryption and decryption operations.
Is it possible or is there a way I can configure the Jasypt encryptor using my own SecretKey instead of setting a password?
Like in Java Cipher, we do...
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, MY_SECRET_KEY);
I see that Jasypt internally uses the String password to create the SecretKey and initiate the Java Cipher. Is it possible to provide my Key here?
PBE stands for Password Based Encryption.
That means instead of requiring a SecretKey it needs a passphrase which will then be used to generate the key by hashing it many times.
So manually settings the SecretKey for a PBE-encryption would invalidate it's purpose. For exactly that reason StandardPBEStringEncryptor does not allow this. (see it's doc for more information)
If you want to use your own SecretKey, simply use a standard encryption function.

What is the proper way to perform authenticated encryption in Java?

Authenticated encryption requires that we use some accepted standard for encrypting and authenticating a message. So we both encrypt the message and compute a MAC on the message to verify it has not been tampered with.
This question outlines a way to perform password based key strengthening and encryption:
/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
/* Encrypt the message. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes("UTF-8"));
But as far as I can tell, this does not compute any MAC on the ciphertext and so would be insecure. What is the accepted standard for performing authenticated encryption in Java?
I would recommend using GCM mode encryption. It is included in the latest JDK (1.7) by default. It uses a counter mode encryption (a stream cipher, no padding required) and adds an authentication tag. One big advantage is that it requires only a single key, whereas HMAC adds another key to the mix. Bouncy Castle has an implementation as well, which is moslty compatible with one provided by Oracle.
GCM mode encryption is also features in a TLS RFC, and in XML encrypt 1.1 (both not final). GCM mode provides all three security features: confidentiality, integrity and authenticity of the data send. The String would be "AES/GCM/NoPadding" instead of the CBC one you are now deploying. As said, make sure you have the latest JDK from Oracle, or have Bouncy Castle provider installed.
Also check out my answer here, which is mostly about String encoding, but I've succesfully tried GCM mode too - see the comment.
When transferring files from one server to another through secure ftp, I use private/public key pairs with the private key residing on the "from" server and the public key residing on the "to" server.
Using private/public key pairs is a secure standard when transferring files.
I believe it would also be a secure means in the context of a Java application.
Check out Generating and Verifying Signatures and Generate Public and Private Keys
for more details on using a private/public key pair setup for digital signatures in Java.

Categories