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

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.

Related

Java 8 using ECIES cipher with a SealedObject fails with 'NullPointerException' - string cannot be null

I am trying to use a ECIES cipher to instantiate a SealedObject, but it fails with a NullPointerException. I am using Java JDK1.8.0_72 with Bouncy Castle bcprov-jdk15on v1.53 running on Windows 10. The code looks like this:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECIES");
kpg.initialize(new ECGenParameterSpec("secp256r1"));
KeyPair keyPair = kpg.generateKeyPair();
Cipher cipher = Cipher.getInstance("ECIES");
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
String toEncrypt = "Hello";
// Check that cipher works ok
cipher.doFinal(toEncrypt.getBytes());
// Using a SealedObject to encrypt the same string fails with a NullPointerException
SealedObject sealedObject = new SealedObject(toEncrypt, cipher);
The code successfully calls 'cipher.doFinal()' but fails when instantiating the SealedObject. The stack trace is:
java.lang.NullPointerException: string cannot be null
at org.bouncycastle.asn1.ASN1OctetString.<init>(Unknown Source)
at org.bouncycastle.asn1.DEROctetString.<init>(Unknown Source)
at org.bouncycastle.jcajce.provider.asymmetric.ies.AlgorithmParametersSpi.engineGetEncoded(Unknown Source)
at java.security.AlgorithmParameters.getEncoded(AlgorithmParameters.java:362)
at javax.crypto.SealedObject.<init>(SealedObject.java:179)
I'm trying to avoid specifying a particular provider (i.e. Bouncy Castle) and avoiding any provider-specific classes such as IESParameterSpec because the component uses external configuration to specify the algorithms to be used. The component is intended to be used as part of a messaging library in a fluid cluster of nodes where each node may use a different algorithm for encryption, so a SealedObject seems like a reasonable choice because it can be used to pass the algorithm used (any message that uses encryption uses the receiver's public key so the receiver must have the corresponding private key to decrypt the message).
Any thoughts or suggestions would be most welcome.
David Hook at Bouncy Castle had a look and identified an issue in org.bouncycastle.jcajce.provider.asymmetric.ies.AlgorithmParametersSpi.engineGetEncoded and provided a fix in 1.55b04. I tested this out and it has resolved this issue.
Thanks again for your help Maarten.

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);

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.

Detecting incorrect key using AES/GCM in 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.

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