With the below code i am using to do get the parameters required for AES encryption:
s_key is the file provided which contains the key that will be used to encrypt and decrypt
File file = new File("/home/roxane/key");
String passwordStr = FileUtils.readFileToString(file, "UTF-8");
String outputPath = "/home/roxane/test1";
String inputPath = "/home/roxane/test";
// Generate random 8 bytes salt
SecureRandom random = new SecureRandom();
byte salt[] = new byte[8];
random.nextBytes(salt);
// Derive 32 bytes key (AES_256) and 16 bytes IV
byte[] password = passwordStr.getBytes(StandardCharsets.UTF_8);
OpenSSLPBEParametersGenerator pbeGenerator = new OpenSSLPBEParametersGenerator(new MD5Digest()); // SHA256 as of v1.1.0 (if in OpenSSL the default digest is applied)
pbeGenerator.init(password, salt);
ParametersWithIV parameters = (ParametersWithIV) pbeGenerator.generateDerivedParameters(256, 128);// keySize, ivSize in bits
How to segragate the Key and other parameters (IV and Salt) from ParametersWithIV and print to console??
CodePudding user response:
Passphrase and salt can be determined via the OpenSSLPBEParametersGenerator
instance, key and IV via the ParametersWithIV
instance. The following code:
import java.nio.charset.StandardCharsets;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.generators.OpenSSLPBEParametersGenerator;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Hex;
...
byte[] passwordIn = "mypassword".getBytes(StandardCharsets.UTF_8);
byte[] saltIn = Hex.decode("1011121314151617");
OpenSSLPBEParametersGenerator pbeGenerator = new OpenSSLPBEParametersGenerator(new MD5Digest());
pbeGenerator.init(passwordIn, saltIn);
byte[] password = pbeGenerator.getPassword();
byte[] salt = pbeGenerator.getSalt();
int iterationCount = pbeGenerator.getIterationCount();
ParametersWithIV parameters = (ParametersWithIV) pbeGenerator.generateDerivedParameters(256, 128);
byte[] iv = parameters.getIV();
KeyParameter keyParameter = (KeyParameter)parameters.getParameters();
byte[] key = keyParameter.getKey();
System.out.println("Password: " Hex.toHexString(password));
System.out.println("Salt: " Hex.toHexString(salt));
System.out.println("Iterations: " iterationCount);
System.out.println("IV: " Hex.toHexString(iv));
System.out.println("Key: " Hex.toHexString(key));
gives the output:
Password: 6d7970617373776f7264
Salt: 1011121314151617
Iterations: 1
IV: 3146b93c40ea036ca6a5fa6d28913e3b
Key: 9d75d2a0fd8625115ff0814a71a6f23ffb131e8afcd79dd90542956b8156a0ad
Key and IV can be easily verified with OpenSSL:
openssl enc -e -aes256 -md md5 -S 1011121314151617 -k mypassword -P
returns:
salt=1011121314151617
key=9D75D2A0FD8625115FF0814A71A6F23FFB131E8AFCD79DD90542956B8156A0AD
iv =3146B93C40EA036CA6A5FA6D28913E3B