How to encrypt/decrypt files with PBE AES using BouncyCastle Lightweight API? - java

I'm trying to encrypt/decrypt files with PBE using AES. I'm using Bouncy Casle library(lightweight API), because I need to ignoring restrictions on key length. I found function and changed some code in it.
public void decryptLW(InputStream in, OutputStream out, String password, byte[] salt, final int iterationCount) throws Exception {
PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(new SHA256Digest());
char[] passwordChars = password.toCharArray();
final byte[] pkcs12PasswordBytes = PBEParametersGenerator.PKCS12PasswordToBytes(passwordChars);
pGen.init(pkcs12PasswordBytes, salt, iterationCount);
CBCBlockCipher aesCBC = new CBCBlockCipher(new AESEngine());
ParametersWithIV aesCBCParams = (ParametersWithIV) pGen.generateDerivedParameters(256, 128);
aesCBC.init(false, aesCBCParams);
PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(aesCBC, new PKCS7Padding());
try {
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
byte[] plainTemp = new byte[aesCipher.getOutputSize(buf.length)];
int offset = aesCipher.processBytes(buf, 0, buf.length, plainTemp, 0);
int last = aesCipher.doFinal(plainTemp, offset);
final byte[] plain = new byte[offset + last];
System.arraycopy(plainTemp, 0, plain, 0, plain.length);
out.write(plain, 0, numRead);
}
out.close();
in.close();
} catch (java.io.IOException e) {
}
}
And I have an error:
org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted
at org.bouncycastle.crypto.paddings.PKCS7Padding.padCount(Unknown Source)
at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.doFinal(Unknown Source)
What can I do to remove this error? And what I must to change in this function to get ability to encrypt files.

Finally, I found problem, I don't have initialized aesCipher. When I added method aesCipher.init(true, aesCBCParams); it started working.
And also I changed some code:
int numRead = 0;
while ((numRead = fin.read(buf)) >= 0) {
if (numRead == 1024) {
byte[] plainTemp = new byte[aesCipher.getUpdateOutputSize(numRead)];
int offset = aesCipher.processBytes(buf, 0, numRead, plainTemp, 0);
final byte[] plain = new byte[offset];
System.arraycopy(plainTemp, 0, plain, 0, plain.length);
fout.write(plain, 0, plain.length);
} else {
byte[] plainTemp = new byte[aesCipher.getOutputSize(numRead)];
int offset = aesCipher.processBytes(buf, 0, numRead, plainTemp, 0);
int last = aesCipher.doFinal(plainTemp, offset);
final byte[] plain = new byte[offset + last];
System.arraycopy(plainTemp, 0, plain, 0, plain.length);
fout.write(plain, 0, plain.length);
}
}

You have a problem with your padding. This may mean that the incoming cyphertext was encrypted with a different padding, not PKCS7. It may mean that the incoming cyphertext was encrypted in a different mode (not CBC). It may mean that you have the wrong key, so the last block decrypts as random. If your message is only one block long then it may mean you have a faulty IV, so again the padding is corrupt.
You need to check that the key, mode, padding and IV are identical at both ends. This means checking key and IV byte by byte.

Related

AES Encryption and Decryption not getting decrypted word in print statements but shows up in debugger

Hi I'm working on a socket programming project where it is a encrypted client and server. I have all the code working to create public keys, private keys, aes secret encryption and decryption. The issue is when I sent my encrypted values over to the server, it is missing the first few values of the encrypted values. But when I run it through the debugger and add breakpoints it prints the right decrypted value.
For this say my text is "jesus" this is my client class for example.
Client.java
try {
IvParameterSpec iv = new IvParameterSpec(initVector);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8));
System.out.println("encrypted string: "
+ Base64.getEncoder().encodeToString(encrypted));
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(Strings[] args) {
// I have all the code for making keys and creating the Socket connection ( all of this stuff works)
System.out.println("What is your port number");
port = scanner.nextInt();
System.out.println("What is your ip address");
ipAddress = scanner.next();
System.out.println("What is your client's private key file");
privateKeyFile = scanner.next();
System.out.println("What is your server's public key file");
publicKeyFile = scanner.next();
System.out.println("What is your text string");
textString = scanner.next();
Socket socket = new Socket(ipAddress, port);
DataInputStream input = new DataInputStream(socket.getInputStream());
// sends output to the socket
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
PrivateKey clientPrivateKey = loadPrivateKey(privateKeyFile, "RSA");
PublicKey serverPublicKey = loadPublicKey(publicKeyFile, "RSA");
// I have more but essentially that is part of it
// stuff that isn't working
SecureRandom sr = new SecureRandom();
KeyGenerator kg= KeyGenerator.getInstance("AES");
kg.init(256, sr);
SecretKey key256AES = kg.generateKey();
String encodedTextString = new String(Base64.getEncoder().encode(
textString.getBytes(StandardCharsets.UTF_8)));
Integer textStringLengthFromBytes = textByte.length;
byte[] textSignature = signDigitalSignature(textByte, clientPrivateKey, "SHA512withRSA");
byte[] IV = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
String cipherText = encrypt(key256AES, IV, textString);
System.out.println("Cipher" + cipherText);
output.write(textStringLengthFromBytes);
output.write(textSignature);
output.write(cipherText.getBytes(StandardCharsets.UTF_8));
}
Server.java
public static String decrypt(SecretKey key, byte[] initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] plainText = cipher.doFinal(Base64.getDecoder()
.decode(encrypted));
return new String(plainText);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String args[]){
// round 2 for this project I have to get the size of the plaintext string and //the aesEncryptedString and the actual cipher text
Integer size = in.readInt();
System.out.println("size" + size);
byte[] textSignatureFromClient = new byte[256];
in.readFully(textSignatureFromClient);
System.out.println("textSignatureFromClient" +
Arrays.toString(textSignatureFromClient));
// having issues with this part below
String cipherText = in.readLine();
System.out.println("Cipher " + cipherText);
byte[] IV = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
String decryptedVal = decrypt(AESSecretKey, IV, cipherText);
System.out.println("Text" + decryptedVal);
}
Here is an output of what values are stored in the ciphers:
Client ciphertext says: V5VoP7K/Bzzj5291kd3WYg==
Server ciphertext says: oP7K/Bzzj5291kd3WYg==
Here is the error I get as well:
java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 20
But when I debug, I pass over the decrypt line in the the server and it gets me the word jesus in plaintext both in the debugger variables and in the console. Also I apologize for how messy my code is. I'm going to clean it and modularize it more once all my requirements are met.
I have absolutely no idea why this worked but I this is what my Server.java looks like now. I just added "" at the end of in.readline() because I noticed when I added comments it got the full cipher. Additionally, it is receiving the text signature before the cipher with no issues.
Server.java
byte[] textSignatureFromClient = new byte[256];
in.readFully(textSignatureFromClient);
String cipherText = in.readLine() + "";
try {
byte[] IV = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
String decryptedVal = decrypt(AESSecretKey, IV, cipherText.trim());
System.out.println("Decrypted Text: " + decryptedVal);
}
catch(Exception e){
System.out.println("Decryption error" + e);
}
Client.java
String encodedTextString = new String(Base64.getEncoder().encode(
textString.getBytes(StandardCharsets.UTF_8)));
byte[] textByte = encodedTextString.getBytes();
byte[] textSignature = signDigitalSignature(textByte, clientPrivateKey, "SHA512withRSA");
output.write(textSignature);
output.flush();
String cipherText = encrypt(key256AES, IV, textString);
System.out.println("Cipher" + cipherText);
output.write(cipherText.getBytes(StandardCharsets.UTF_8));
output.flush(); ```

java decrypt by X509 public key

As I am trying to encrypt the text to PKCS8 private key and decrypt by X509 public key.
public static String decryptByPublicKey(String data, String keyHash) {
final String KEY_ALGORITHM = "RSA";
final int MAX_DECRYPT_BLOCK = 128;
try {
byte[] keyBytes = Base64.getDecoder().decode(keyHash);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(publicKeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
byte[] buffer =data.getBytes();
int inputLen = buffer.length;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(buffer, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(buffer, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return new String(decryptedData, "UTF-8");
} catch (Exception e) {
logger.error("decryptByPublicKey - Exception: ", e);
e.printStackTrace();
}
return null;
}
It shows BadPaddingException.
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2223)
Since, I have tried to reverse the method (encrypt by public key and decrypt by private key), it is okay.
Do anyone can tell me what's the problem is?
From the error given
It shows BadPaddingException.javax.crypto.BadPaddingException: Decryption error
Please check the size of your buffer on (int inputLen = buffer.length). You need to pad out the data to be the required block size.
You should only call doFinal() once, the last time. Every other time you should be calling update().
But it doesn't make sense to do this. Encrypting with a private key isn't encryption, it is digital signing.

Encryption in C# and decryption in Java

I am doing Encryption in C# for windows phone 8.1 app and I need to decrypt it using java.
Here is my Encryption code
public static String encrypt(String plaintext, KeyParameter keyParam)
{
byte[] ivData = new byte[AES_NIVBITS / 8];
Random r = new Random();
r.NextBytes(ivData);
IBlockCipherPadding padding = new Pkcs7Padding();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()), padding);
ICipherParameters param = new ParametersWithIV(keyParam, ivData);
cipher.Reset();
cipher.Init(true, param);
byte[] bytesDec = Encoding.GetEncoding("iso-8859-1").GetBytes(plaintext);
byte[] bytesEnc = null;
int buflen = cipher.GetOutputSize(bytesDec.Length);
System.Diagnostics.Debug.WriteLine("enc length " + buflen);
bytesEnc = new byte[buflen];
int nBytesEnc = cipher.ProcessBytes(bytesDec, 0, bytesDec.Length, bytesEnc, 0);
nBytesEnc += cipher.DoFinal(bytesEnc, nBytesEnc);
if (nBytesEnc != bytesEnc.Length)
{
throw new Exception("Unexpected behaviour : getOutputSize value incorrect");
}
byte[] bytesAll = new byte[ivData.Length + bytesEnc.Length];
Array.Copy(ivData, 0, bytesAll, 0, ivData.Length);
Array.Copy(bytesEnc, 0, bytesAll, ivData.Length, bytesEnc.Length);
byte[] bytesAllb64 = Base64.Encode(bytesAll);
return Encoding.GetEncoding("iso-8859-1").GetString(bytesAllb64, 0, bytesAllb64.Length);
}
And this is the java code for decryption
public static String decodeBase64Aes(String encodedciphertext, KeyParameter keyParam) throws Exception
{
byte[] bytesEnc = Base64.decode(encodedciphertext.getBytes(ISO8859));
int nIvBytes = AES_NIVBITS / 8;
byte[] ivBytes = new byte[nIvBytes];
System.arraycopy(bytesEnc, 0, ivBytes, 0, nIvBytes);
CipherParameters params = new ParametersWithIV(keyParam, ivBytes);
BlockCipherPadding padding = new PKCS7Padding();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
cipher.reset();
cipher.init(false, params);
byte[] bytesDec = null;
int buflen = cipher.getOutputSize(bytesEnc.length - nIvBytes);
byte[] workingBuffer = new byte[buflen];
int len = cipher.processBytes(bytesEnc, nIvBytes, bytesEnc.length - nIvBytes, workingBuffer, 0);
len += cipher.doFinal(workingBuffer, len);
bytesDec = new byte[len];
System.arraycopy(workingBuffer, 0, bytesDec, 0, len);
return new String(bytesDec, ISO8859);
}
When I am encrypting it it's working fine but when I test decryption using the encrypted text I got and key, it throws
Exception in thread "main" org.bouncycastle.crypto.DataLengthException: last block incomplete in decryption
I can only change the c# part. Any help would be highly appreciated???
Key -> 8fe3f8b34e87744c175aae43cc52ee13
'Hello World' -> Nb90n51LqK13LzpalV7qTs7YJqe9m+Ni9uA/U7tU06Y=
The Exception Comes on line
len += cipher.doFinal(workingBuffer, len);
When I encrypt "Hello World" from java using the same key from the encryption method I have on my server I get
uWMz8ZIPh+3jnGtwxpuyK9Qht7BJV4RQ/Iet9JeTrTk=
EDIT ------
Updated to working code.
Base 64 does not give same length as the original one and that's why I was gettting that error. I have updated the code with the correct one.

AES-GCM: AEADBadTagException: mac check in GCM failed

While trying to implement AES-GCM for the first time, we are facing issue in generating AuthenticationTag, Encrypted cipher & GCM mac check fails in the end. For out current implementation tag[] is being populated but byte[] encrypted remains empty. And because of this cipher.doFinal(data1, offset) gives 'mac check in GCM failed'. It appears to be some issue around the size of byte arrays, can someone please share on what basis should the output buffer size be determined? Should this be done in chunks?
Any pointers/links to AES-GCM implementation will be highly appreciated.
Following is our implementation:
public class GCMTest {
public static void main(String[] args) throws Exception {
//***********************************************************
//Key
byte[] key = MessageDigest.getInstance("MD5").digest("1234567890123456".getBytes("UTF-8"));//this is the random key
//Iv
SecureRandom srand = SecureRandom.getInstance("SHA1PRNG");
byte[] iv = new byte[256];
srand.nextBytes(iv);
//Input
byte[] data="inputPlainText".getBytes();
final GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(16 * Byte.SIZE, iv);
//***********************************************************
//Encryption
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), gcmParameterSpec);
cipher.updateAAD("MyAAD".getBytes("UTF-8"));
//Encrypted output
final byte[] encrypted = new byte[cipher.getOutputSize(data.length)];
cipher.update(data, 0, data.length, encrypted, 0); //Not being updated for current data.
//Tag output
byte[] tag = new byte[cipher.getOutputSize(data.length)];
cipher.doFinal(tag, 0);
//***********************************************************
//Decryption
final SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
cipher.updateAAD("MyAAD".getBytes("UTF-8"));
//What size should be assigned to outputBuffer?
final byte[] data1 = new byte[256];
int offset = cipher.update(encrypted, 0, encrypted.length, data1, 0);
cipher.update(tag, 0, tag.length, data1, offset);
cipher.doFinal(data1, offset);
boolean isValid = checkEquals(data, data1);
System.out.println("isValid :"+isValid);
}
private static boolean checkEquals(byte[] a, byte[] b)
{
int diff = a.length ^ b.length;
for(int i = 0; i < a.length && i < b.length; i++)
diff |= a[i] ^ b[i];
return diff == 0;
}
}
It gives following exception:
Exception in thread "main" javax.crypto.AEADBadTagException: mac check in GCM failed
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$AEADGenericBlockCipher.doFinal(Unknown Source)
at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(Cipher.java:2068)
at GCMTest.main(GCMTest.java:56)
Thanks in advance!!
I was having this same issue. For me, it had to do with encoding the string. I ended up doing:
Get ASCII bytes from string you want to encrypt (UTF-8 in your case)
Encrypt bytes
Encode bytes in Base64 string
Then to decrypt string I did:
Decode encrypted string to Base64 bytes
Decrypt Base64 bytes
Create new string using ASCII.
Here is the code :
private String encrypt(String src) {
byte[] srcBytes = src.getBytes(StandardCharsets.US_ASCII);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, secureRandom);
byte[] cipherText = cipher.doFinal(srcBytes);
byte[] encryptedBytes = new byte[12 + cipherText.length];
System.arraycopy(ivBytes, 0, encryptedBytes, 0, 12);
System.arraycopy(cipherText, 0, encryptedBytes, 12, cipherText.length);
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
}
private String decrypt(String encryptedString) {
byte[] encryptedBytes = Base64.decode(encryptedString, Base64.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, secretKey, new GCMParameterSpec(128, encryptedBytes, 0, 12));
byte[] decryptedBytes = cipher.doFinal(encryptedBytes, 12, encryptedBytes.length-12);
return Base64.encodeToString(decryptedBytes, Base64.DEFAULT);
}
Any variables I didn't include how to initialize them can be inferred from the java docs. I was trying to do this in Android so I'm not sure how different it is. I found this post to be incredibly helpful: Java AES/GCM/NoPadding - What is cipher.getIV() giving me?
you should update section code
error section code:
//What size should be assigned to outputBuffer?
final byte[] data1 = new byte[256];
int offset = cipher.update(encrypted, 0, encrypted.length, data1, 0);
cipher.update(tag, 0, tag.length, data1, offset);
cipher.doFinal(data1, offset);
update the new code:
final byte[] data1 = new byte[encrypted.length];
int offset = cipher.update(encrypted, 0, encrypted.length, data1, 0);
offset += cipher.update(tag, 0, tag.length, data1, offset);
cipher.doFinal(data1, offset);

TripleDES encryption error in java

I'm following this tutorial to use 3DES encryption, and i needed to make some changes in cipher settings, so here's my code:
public class TripleDES {
public static int MAX_KEY_LENGTH = DESedeKeySpec.DES_EDE_KEY_LEN;
private static String ENCRYPTION_KEY_TYPE = "DESede";
private static String ENCRYPTION_ALGORITHM = "DESede/ECB/PKCS7Padding";
private final SecretKeySpec keySpec;
private final static String LOG = "TripleDES";
public TripleDES(String passphrase) {
byte[] key;
try {
// get bytes representation of the password
key = passphrase.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
key = padKeyToLength(key, MAX_KEY_LENGTH);
key = addParity(key);
keySpec = new SecretKeySpec(key, ENCRYPTION_KEY_TYPE);
}
// !!! - see post below
private byte[] padKeyToLength(byte[] key, int len) {
byte[] newKey = new byte[len];
System.arraycopy(key, 0, newKey, 0, Math.min(key.length, len));
return newKey;
}
// standard stuff
public byte[] encrypt(String message) throws GeneralSecurityException, UnsupportedEncodingException {
byte[] unencrypted = message.getBytes("UTF8");
return doCipher(unencrypted, Cipher.ENCRYPT_MODE);
}
public byte[] decrypt(byte[] encrypted) throws GeneralSecurityException {
return doCipher(encrypted, Cipher.DECRYPT_MODE);
}
private byte[] doCipher(byte[] original, int mode)
throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
// IV = 0 is yet another issue, we'll ignore it here
// IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
cipher.init(mode, keySpec); //, iv);
return cipher.doFinal(original);
}
// Takes a 7-byte quantity and returns a valid 8-byte DES key.
// The input and output bytes are big-endian, where the most significant
// byte is in element 0.
public static byte[] addParity(byte[] in) {
byte[] result = new byte[8];
// Keeps track of the bit position in the result
int resultIx = 1;
// Used to keep track of the number of 1 bits in each 7-bit chunk
int bitCount = 0;
// Process each of the 56 bits
for (int i = 0; i < 56; i++) {
// Get the bit at bit position i
boolean bit = (in[6 - i / 8] & (1 << (i % 8))) > 0;
// If set, set the corresponding bit in the result
if (bit) {
result[7 - resultIx / 8] |= (1 << (resultIx % 8)) & 0xFF;
bitCount++;
}
// Set the parity bit after every 7 bits
if ((i + 1) % 7 == 0) {
if (bitCount % 2 == 0) {
// Set low-order bit (parity bit) if bit count is even
result[7 - resultIx / 8] |= 1;
}
resultIx++;
bitCount = 0;
}
resultIx++;
}
Log.d(LOG, "result: " + result);
return result;
}
}
But i'm getting InvalidKeyException on this line:
cipher.init(mode, keySpec);
LogCat:
W/System.err(758): java.security.InvalidKeyException: src.length=8 srcPos=8 dst.length=8 dstPos=0 length=8
W/System.err(758): at org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(JCEBlockCipher.java:584)
W/System.err(758): at org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(JCEBlockCipher.java:631)
W/System.err(758): at javax.crypto.Cipher.init(Cipher.java:511)
W/System.err(758): at javax.crypto.Cipher.init(Cipher.java:471)
I'm new on encrytion so i probably overlook something but i cannot find what it is. Any help is appreciated...
Triple DES requires a 24 byte key, not an 8 byte one.
I've found solution by changing these lines:
try {
// get bytes representation of the password
key = passphrase.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
key = padKeyToLength(key, MAX_KEY_LENGTH);
key = addParity(key);
keySpec = new SecretKeySpec(key, ENCRYPTION_KEY_TYPE);
into these:
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] keyBytes = GetKeyAsBytes(key);
keySpec = new SecretKeySpec(keyBytes, "DESede");
while GetKeyAsBytes method is this:
public byte[] GetKeyAsBytes(String key) {
byte[] keyBytes = new byte[24]; // a Triple DES key is a byte[24] array
for (int i = 0; i < key.length() && i < keyBytes.length; i++)
keyBytes[i] = (byte) key.charAt(i);
return keyBytes;
}

Categories

Resources