I have a Xml which is stored in the String. I need to encrypt it using a session key (AES and 256bit).
I am using following code to generate the key:
public byte[] generateSessionKey() throws NoSuchAlgorithmException, NoSuchProviderException
{
KeyGenerator kgen = KeyGenerator.getInstance("AES","BC");
kgen.init(SYMMETRIC_KEY_SIZE);
SecretKey key = kgen.generateKey();
byte[] symmKey = key.getEncoded();
return symmKey;
}
Using following code to encrypt data with session key:
public byte[] encryptUsingSessionKey(byte[] skey, byte[] data) throws InvalidCipherTextException
{
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new AESEngine(), new PKCS7Padding());
cipher.init(true, new KeyParameter(skey));
int outputSize = cipher.getOutputSize(data.length);
byte[] tempOP = new byte[outputSize];
int processLen = cipher.processBytes(data, 0, data.length, tempOP, 0);
int outputLen = cipher.doFinal(tempOP, processLen);
byte[] result = new byte[processLen + outputLen];
System.arraycopy(tempOP, 0, result, 0, result.length);
return result;
}
So, I want to know, am I doing it right or wrong?
Is the session key private, if not there is a security issue.
You are not specifying an encryption mode, it is best to be explicit.
Since there does not seem to be an iv and no mode is specified the assumption is the mode is ECB which is insecure, it is better to the CBC mode with a random iv that is prepended to the encrypted data for use during decryption.
Also missing is encryption authentication and the key generation is weak, it would be better to use a derivation function such as PBKDF2.
Do not use ECB mode, it is insecure, see ECB mode, scroll down to the Penguin.
Consider using a more complete library such as RNCryptor's JMCryptor that includes PBKDF2 key derivation, encryption authentication, random iv and versioning. Also see Specification for RNCryptor for more information.
Related
I'm trying to change encryption algorithm of existing project. But i have a little bit confusion. When i use "PBEWithHmacSHA512AndAES_256" as a parameter, it produce different result but when i use "PBEWithMD5AndDES" as a parameter it produce same result. My functions are :
public static synchronized String encrypt1(final String textToEncrypt, final String pathPublicKey) throws Exception {
final KeySpec pbeKeySpec = new PBEKeySpec(DbKeyHandler.getDbKey(pathPublicKey).toCharArray());
final SecretKey pbeKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(pbeKeySpec);
// Prepare the parameter to the ciphers
final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
final Cipher cipher = Cipher.getInstance(pbeKey.getAlgorithm());
// Create the ciphers
cipher.init(Cipher.ENCRYPT_MODE, pbeKey, paramSpec);
// Encode the string into bytes using utf-8
final byte[] utf8 = textToEncrypt.getBytes("UTF8");
// Encrypt
final byte[] enc = cipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
public static synchronized String encrypt2 (final String textToEncrypt, final String pathPublicKey) throws Exception {
final KeySpec pbeKeySpec = new PBEKeySpec(DbKeyHandler.getDbKey(pathPublicKey).toCharArray());
final SecretKey pbeKey = SecretKeyFactory.getInstance("PBEWithHmacSHA512AndAES_256").generateSecret(pbeKeySpec);
// Prepare the parameter to the ciphers
final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
final Cipher cipher = Cipher.getInstance(pbeKey.getAlgorithm());
// Create the ciphers
cipher.init(Cipher.ENCRYPT_MODE, pbeKey, paramSpec);
// Encode the string into bytes using utf-8
final byte[] utf8 = textToEncrypt.getBytes("UTF8");
// Encrypt
final byte[] enc = cipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
Any suggestions, ideas will help me to figure out what's going on here.
Also this is produce different results:
KeyStore keyStore = KeyStore.getInstance("JCEKS");
keyStore.load(new FileInputStream((pathOfJKSfile)), password.toCharArray());
Key key = keyStore.getKey(keyName, keyPass.toCharArray());
byte[] raw = key.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "PBEWithHmacSHA512AndAES_256");
final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);
final Cipher cipherEncrypt = Cipher.getInstance(ALGORITHM);
cipherEncrypt.init(Cipher.ENCRYPT_MODE, secretKeySpec, paramSpec);
final byte[] enc = cipherEncrypt.doFinal(messageBytes);
System.out.println( new sun.misc.BASE64Encoder().encode(enc));
And i know that cipher.init() using "JceSecurity.RANDOM" for pruducing different results.
Both algorithms, PBEWithHmacSHA512AndAES_256 and PBEWithMD5AndDES, first generate an encryption key by processing a password, a salt and an iteration count (using HmacSHA512 and MD5, respectively) and then encrypt the plain text (with AES-256 and DES, respectively) using this key and the CBC-mode. When the Cipher-instance is initialized, a pseudo-random initialization vector (IV) is generated that is required for the CBC- mode.
In the context of PBEWithHmacSHA512AndAES_256, the IV is generated using the SecureRandom implementation of the highest-priority installed provider, at least for the Cipher#init()-method used in the code (note that there are several overloads of the Cipher#init()-method and that a SecureRandom-instance can also be passed explicitly). I.e. with each Cipher-initialization a new (random) IV is generated and therefore the encrypted text is always different, even for an identical plain text. For this reason, the encrypted text in your examples changes in this context.
In the context of PBEWithMD5AndDES, the IV is only determined by the password, the salt, the iteration count (and of course the MD5-hash-algorithm itself). Therefore, the IV and the encrypted text do not change in case of repetition (provided that password, salt, iteration count etc. are the same). For this reason, the encrypted text in your example does not change in this context.
The generation of a new, random IV during the Cipher-initalization makes sense with regard to the following requirements for the IV: For security reasons, an IV in CBC-mode (btw this also applies to other modes) may only be used once under the same key. In addition the IV must be unpredictable.
PBEWithMD5AndDES is deprecated.
EDIT:
The use of an IV is standard nowadays (for security reasons). A lot of information can be found on the Internet on this topic e.g. here. In the following I will only describe a few basic things.
The IV used for encryption must be stored in some way because it is required for decryption. The IV does not have to be kept secret, so that it is usually concatenated with the encrypted data (e.g. before the encrypted data) and stored together with them. During decryption, both parts can be separated because the length of the IV is known (16 Byte for AES). E.g for the concatenation in the encryption-method something like the following is used (let iv and enc be the byte-arrays with the IV and the encrypted data, respectively):
byte[] result = new byte[enc.length + iv.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(enc, 0, result, iv.length, enc.length);
and in the decryption-method the corresponding counterpart (having in mind that the length of an IV in AES is 16 Byte).
In the encryption-method the IV can be determined with Cipher#getIV() (this must of course happen after calling Cipher#init()).
In the decryption-method you have to pass the IV to the PBEParameterSpec-ctor (e.g. let iv be the byte-array with the IV):
IvParameterSpec ivSpec = new IvParameterSpec(iv);
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount, ivSpec);
The generation of an IV can also take place outside the Cipher-class, see e.g. Generating random IV for AES in Java. Then you have to pass that IV in the encryption-method in the same way as above described for the decryption-method.
Note, in connection with an IV some points have to be considered e.g. using a mode without an IV (e.g. ECB), using an IV consisting exclusively of 0-values, using a predictable IV or using an IV more than once under the same key etc. drastically reduces security in general, see e.g. here!
Thank you for taking you time to assist me with this!
THIS POST HAS BEEN EDITED FOR LESS INFORMATION SEE THE EDITED PART
Well I have spend ours of research on this matter and I ended up with a working piece of code..
But Encryption is not a place to make mistakes, and I wanted to ask if my code is actualy secure! It's really important for me because I want to implement it to a program so my code is...
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
public class EncryptFile{
private static final String FILE_IN = "./EncryptFile.java";
private static final String FILE_ENCR = "./EncryptFile_encr.java";
private static final String FILE_DECR = "./EncryptFile_decr.java";
public static void main(String []args){
try
{
Encryption("passwordisnottheactual", Files.readAllBytes(Paths.get(FILE_IN)));
Decryption("passwordisnottheactual");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
private static void Encryption(String Key, byte[] byteArray) throws Exception
{
// Decode the base64 encoded Key
byte[] decodedKey = Base64.getDecoder().decode(Key);
// Rebuild the key using SecretKeySpec
SecretKey secretKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
// Cipher gets AES Algorithm instance
Cipher AesCipher = Cipher.getInstance("AES");
//Initialize AesCipher with Encryption Mode, Our Key and A ?SecureRandom?
AesCipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom());
byte[] byteCipherText = AesCipher.doFinal(byteArray);
//Write Bytes To File
Files.write(Paths.get(FILE_ENCR), byteCipherText);
}
private static void Decryption(String Key) throws Exception
{
//Ddecode the base64 encoded string
byte[] decodedKey = Base64.getDecoder().decode(Key);
//Rebuild key using SecretKeySpec
SecretKey secretKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
//Read All The Bytes From The File
byte[] cipherText = Files.readAllBytes(Paths.get(FILE_ENCR));
//Cipher gets AES Algorithm Instance
Cipher AesCipher = Cipher.getInstance("AES");
//Initialize it in Decrypt mode, with our Key, and a ?SecureRandom?
AesCipher.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom());
byte[] bytePlainText = AesCipher.doFinal(cipherText);
Files.write(Paths.get(FILE_DECR), bytePlainText);
}
}
EDIT
Possible duplicate of Simple Java AES encrypt/decrypt example – JFPicard
Well it could be but these answers Use IVParameterSpec and I wanted to know if
this line of code is actually secure or if it is bad practice:
AesCipher.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom());
because I use a new SecureRandom() every time,
and I haven't seen anyone use a SecureRandom object like this.
Encryption key
The password is passes as a string but the Encryption function Base64 decoded it, that is a coding error.
When a password is used the encryption key should be derived from it with the PBKDF2 (aka Rfc2898DeriveBytes) function.
When using key derivation the salt and iteration count needs to be available for decryption, often they are provided in a prefix to the encrypted data.
Encryption mode
No encryption mode is supplied.
Use CBC mode with a random IV.
Just prefix the encrypted data with the IV for use on decryption.
Padding
AES is a block cipher and as such requires the input data size to be a multiple of the block size.
Specify PKCS#7 (née PKCS#5) padding, it will add padding on encryption and remove it on decryption.
On decryption do not return "padding" errors, they can provide a "Padding Oracle" attack.
Explicit
Specify all encryption parameters and sizes.
Do not rely on implementation defaults.
Encryption authentication
Consider if there is a need to know if the data is decrypted correctly.
Versioning
Add a version indicator so that if changes are necessary later there is an compatibility path.
Or consider using RNCryptor which handles all this and more.
Update: (thx Andy for the comment)
If GCM mode is available and interoperability across platforms and libraries is not an issue GCM is arguably a better encryption mode. GCM has authentication and padding build-in making it more robust and an easier secure solution.
I have implemented AES encryption in java, but the algorithm is not accepted by team as it is implemented in ECB mode which is not security compliant.I am very new to cryptography and Security requirements.
Can someone please help me changing algorithm to CBC mode. I have attached my code implemented in ECB mode.
public String encrypt(String plainPwd)
{
byte[] outputBytes = new byte[] {};
String returnString = "";
try
{
byte[] raw = "XXXXX#XXXXXX.XXX".getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
outputBytes = cipher.doFinal(plainPwd.getBytes("UTF-8"));
if (null != outputBytes)
{
returnString = Base64Encrypter.getInstance().encode(outputBytes);
}
return returnString.trim();
}
catch (Exception e)
{
System.out.println(e);
}
return new String(outputBytes).trim();
}
public String decrypt(String encryptedPwd)
{
byte[] outputBytes = new byte[] {};
try
{
byte[] raw = "XXXXX#XXXXXX.XXX".getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] inputBytes = Base64Encrypter.getInstance().decode(encryptedPwd);
if (null != inputBytes)
{
outputBytes = cipher.doFinal(inputBytes);
}
}
catch (Exception e)
{
System.out.println(e);
}
return new String(outputBytes).trim();
}
Early reply will be highly appreciated.
Thanks in advance
Change the request string from AES to AES/CBC/PKCS5PADDING and add an iv. While padding is not CBC specific it is good to explicitly define all parameters and with few exceptions padding is needed.
For the iv generate a cryptographically secure random number of block size (16-bytes for AES). In order to have the iv available for decryption common practice is to prepend it to the encrypted data, it does not need to be secret.
AES has around 6 different encryption modes. It's important that you use the correct mode for the application that you are using it for. as #eckes says, ECB is fine for small amounts of data where random encrypt/decrypt access is useful. The disadvantage of ECB is that the same input will have the same output, so an attacker could see patterns and may reverse engineer it if there are limited numbers of practical values.
Check out how to choose AES encryption mode for more guidance on picking the correct operation mode.
If your data is short and random ECB might be acceptable (at least not worse than CBC). But it is most likely a good idea to not even try to get this right.
Keep in mind, CBC does also not offer integrity protection. Using a extra HMAC or a dedicated mode for wrapping secrets (AESKeywrap) or using an authenticated mode (AES/GCM) is better. (and this is not only a question of avoiding modifications it also closes a class of attacks against the privacy protection of the protocols).
If the data is not random/predictable you need to use a mode which also uses an IV. In case of CBC Java will pick a random IV if not specified.
However for decrypt (especially if you have a padding which does verification) you need to specify the exactly same IV, so dont forget to retrieve and transmit it. So the (unsecure because not authenticated) encryption becomes:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
byte[] iv = cipher.getIV(); // randomly filled.
...
// on decrypt specify this IV again
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(iv));
This also has the advantage that it actually specifies the padding to use, so you do not depend on the default selection of Java (always specify the full mode string).
I am new to password storage and to Bouncy Castle.
Encryption : Is there a reason to prefer Pkcs5S2ParametersGenerator
over AES to encrypt(salt+hash(password+salt)) ?
An example : How to encrypt and salt the password using BouncyCastle API in Java?
My Java code : is there a better way to get back the salt from the cipher than byte array extraction ?
Here is my java code :
// salt
java.security.SecureRandom rgen = new SecureRandom();
byte[] salt = rgen.generateSeed(20);
// add Bouncy Castle
java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// aes secret key
javax.crypto.KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
Key cleSecrete = kgen.generateKey();
// aes
javax.crypto.Cipher cipher = Cipher.getInstance("AES", "BC");
// sha-256
java.security.MessageDigest sha256 = MessageDigest.getInstance("SHA-256","BC");
// hash the clear password with the salt to avoid collisions
byte[] motDePasseHash = hasherSaler(motDePasseClair.getBytes("UTF-8"),salt);
// Encrypt the hash with the salt to get the salt back
byte[] chiffreBDD = chiffrerSalerHash(salt,motDePasseHash,cleSecrete );
// Store the cipher in DB
...
// Get back the hash and the salt from DB
byte[] deChiffreBDD = deChiffrer(chiffreBDD,cleSecrete );
byte[] saltBDD = extraireOctets(deChiffreBDD,0,19);
byte[] hashBDD = extraireOctets(deChiffreBDD,20,deChiffreBDD.length-1);
// hash the user intput
byte[] motDePasseHashCandidat = hasherSaler(motDePasseClairCandidat.getBytes("UTF-8"),saltBDD);
// Compare hased user input with DB hash
boolean isMotDePasseOK = Arrays.equals(hashBDD,motDePasseHashCandidat);
private final byte[] hasherSaler(byte[] clair,byte[] salt) {
byte[] concat = concatenerOctets(clair,salt);
return sha256.digest(concat);
}
private final byte[] chiffrerSalerHash(byte[] salt,byte[] hash, Key cle) {
cipher.init(true,cle);
return cipher.doFinal(concatenerOctets(salt,hash));
}
private final byte[] deChiffrer(byte[] chiffre, Key cle) {
cipher.init(false,cle);
return cipher.doFinal(chiffre);
}
Thank you.
If you just want to verify a password, you should only use PBKDF2 (or bcrypt/scrypt). A cipher should not be necessary. The salt can be stored without encryption. You may want to use an additional secret to append to the salt that you keep stored in e.g. the source code. Don't forget to store a protocol number with your passwords or you cannot upgrade later on.
As for your code, you should not use generateSeed for salts. You should use update more. "AES" uses ECB mode by default, so specify another mode. Don't rely on defaults. Use a (possibly derived) IV. Don't explicitly use a provider when not necessary.
OK, I could go on for quite a while, but this will have to do for now.
I am in the process of implementing a Java library in Ruby. I have come across the following road block. Is it possible to implement the following code in ruby? Are there any ruby equivalents for byte[], IvParameterSpec, SecretKeySpec ?
private String decrypt(String token)
{
//parse token into its IV and token components
byte[] ivAndToken = Base64.decodeBase64(token);
byte[] iv = new byte[ivLength];
System.arraycopy(ivAndToken, 0, iv, 0, ivLength);
int length = ivAndToken.length - ivLength;
byte[] tokenBytes = new byte[length];
System.arraycopy(ivAndToken, ivLength, tokenBytes, 0, length);
//prepare initialization vector specification
IvParameterSpec spec = new IvParameterSpec(iv);
//create cipher instance based on transformer params
Cipher cipher = Cipher.getInstance(algorithm + mode + padding, CRYPTO_PROVIDER);
//convert key bytes into valid key format
Key key = new SecretKeySpec(Base64.decodeBase64(symkey), algorithm);
//initialize cipher for decryption
cipher.init(Cipher.DECRYPT_MODE, key, spec);
//decrypt the payload
String plaintext = new String(cipher.doFinal(tokenBytes));
return plaintext;
}
You'll probably have to implement both IvParameterSpec and SecretKeySpec on Ruby if you want the algorithm to behave exactly like it does in Java. byte[] is of course just a byte array. You'll probably want to at the docs for them (links above) and also hopefully you understand block cipher operation modes work.
If you don't, SecretKey refers to the symmetric key (eg: the passphrase), and IV is the initialization vector, a cryptographic nonce used to make different encryptions of the same plaintext generate different ciphertext. IV's are needed for all operation modes except ECB. See this wikipedia page for more details.