Illegal block size exception while decrypting the encrypted message digest - java

I want to decrpyt the encrypted message digest. i hav this code in my java program:
String bobSignedMsg = SignedMsg;
//At the receiving end, Bob extracts the msg
// length, the msg text, and the digital
// signature from the signed msg.
//Get the message length.
int MsgLen = Integer.parseInt(bobSignedMsg.trim().substring(bobSignedMsg.length()-6));
System.out.println(
"\n12. Bob's calculated msg len: "
+ MsgLen);
//Get the message text.
String bobMsgText = bobSignedMsg.substring(
0,MsgLen);
System.out.println(
"\n13. Bob's extracted msg text: "
+ bobMsgText);
//Bob knows that everything following the msg
// text except for the four characters at the
// end that indicate the message length is
// the encoded and encrypted version of the
// extended digital signature. He extracts
// it.
String bobExtractedSignature =
bobSignedMsg.substring(
MsgLen,bobSignedMsg.length() - 6);
System.out.println(
"\n14. Bob's extracted extended digital "
+ "signature: "
+ bobExtractedSignature);
byte[] strtodecrypt=bobExtractedSignature.getBytes();
byte[] decryptedCardNo = obj.rsaDecrypt(strtodecrypt,PbkeyPath);
String decryptedform = obj.byteArrayToHexStr(decryptedCardNo);
System.out.println("After Decryption: "+decryptedform);
In the above lines of code
byte[] decryptedCardNo = obj.rsaDecrypt(strtodecrypt,PbkeyPath);
calls the function:
public byte[] rsaDecrypt(byte[] sampleText,String pbkeypath) {
PublicKey pubKey = null;
try {
pubKey = readKeyFromFile(pbkeypath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
cipher.init(Cipher.DECRYPT_MODE, pubKey);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] cipherData = null;
try {
cipherData = cipher.doFinal(sampleText);
// cipherData = cipher.
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cipherData;
}
But it gives the following error:
javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes
at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
I dont understand how to resolve the error for block size exception.....Please if anybody can help me with some ideas it wud be a great help in my project.

Block ciphers, such as RSA, can only encrypt no more than blockSize bytes. If you want to encrypt an arbitrary large amount of data with the same key, you would split it to parts of blockSize and encrypt each block individually. The same applies to decryption.

Related

How can I encrypt a large message with a 512 RSA key?

I want to encrypt a large message and perform a measurement with different key sizes.
public static void generate(int keylen)
{
KeyPairGenerator keygen = null;
try
{
keygen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
keygen.initialize(keylen);
key = keygen.generateKeyPair();
}
When I select 512 as the key size, my program throws the following error message: javax.crypto.IllegalBlockSizeException: Data must not be longer than 53 bytes
public static byte[] encrypt(String message, PublicKey pk)
{
Cipher cipher = null;
try
{
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pk);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
byte[] cipherText = null;
try {
ciphertext = cipher.doFinal(message.getBytes(StandardCharsets.UTF_8));
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return cipherText;
}
I know that the RSA algorithm can only encrypt data that has a maximum byte length of the RSA key length in bits divided with eight minus eleven padding bytes, i.e. number of maximum bytes = key length in bits / 8 - 11.
I also know that 512 is not secure. I want to measure different key sizes with their respective time e.g. 512, 1024, 2048, 4096.....
Is there a way to encrypt the message without using a hybrid method because I also need to measure the time.
I read that there is a method to divide the message into blocks. I am not sure how this works exactly.

What is the algorithm string for 'AGCM256-KW' in java cryptography, to be used in Cipher.getInstance(String algo)?

referring this, I have to encrypt using algorithm AGCM256-­KW. I am using Java Cryptography and I didn't find any such algorithm. Closest I found was AES_256/GCM/NoPadding but it has no KW (Key wrapping).
here is my test code
public void testEncryption(String algo) {
String shared_secret = "LyQnklSrxsk3Ch2+AHi9HoDW#//x1LwM123QP/ln";
try {
// Step 1 - Create SHA-256 digest of the shared key
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(shared_secret.getBytes("UTF-8"));
// Step 2 - generate a 256 bit Content Encryption Key(CEK)
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256);
SecretKey cek = kg.generateKey();
// Step 3 - encrypt the CEK using 256 bit digest generated in Step 1
// and 96 bit random IV. Algorithm should be
// random 96 bit Initialize Vector
SecureRandom random = new SecureRandom();
// byte iv[] = new byte[96];
// random.nextBytes(iv);
byte iv[] = random.generateSeed(96);
System.out.println("IV: " + toBase64(iv) + " length: " + iv.length);
IvParameterSpec ivspec = new IvParameterSpec(iv);
GCMParameterSpec gspec = new GCMParameterSpec(96, iv);
// encrypt
Cipher cipher = Cipher.getInstance(algo);
System.out.println(String.format("CEK Cipher alg:%S provider:%S", cipher.getAlgorithm(),
cipher.getProvider().getName()));
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(digest, "AES"), gspec);
byte[] result = cipher.doFinal(cek.getEncoded());
System.out.println(String.format("Encrypted CEK :%S", toBase64(result)));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Update 1
I think I can use jose4j library which has APIs for JWE.
Yes, the Visa Token Services appear to be using JWE (now RFC 7516) so you can use jose4j for this. Here's some sample code that shows encrypting and decrypting some content with JWE using A256GCMKW and AGCM256:
// shared secret hashed to key from your example
String shared_secret = "LyQnklSrxsk3Ch2+AHi9HoDW#//x1LwM123QP/ln";
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(shared_secret.getBytes("UTF-8"));
JsonWebEncryption jwe = new JsonWebEncryption();
// A256GCMKW for key wrap
jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.A256GCMKW);
// A256GCM for content encryption
jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_256_GCM);
// the key (from above)
jwe.setKey(new SecretKeySpec(digest, "AES"));
// whatever content you want to encrypt
jwe.setPayload("some important content to be encrypted and integrity protected");
// Produce the JWE compact serialization, which is where the actual encryption is done.
// The JWE compact serialization consists of five base64url encoded parts
// combined with a dot ('.') character in the general format of
// <header>.<encrypted key>.<initialization vector>.<ciphertext>.<authentication tag>
String serializedJwe = jwe.getCompactSerialization();
// Do something with the JWE. Like send it to some other party over the clouds
// and through the interwebs.
System.out.println("JWE compact serialization: " + serializedJwe);
// That other party, the receiver, can then use JsonWebEncryption to decrypt the message.
JsonWebEncryption receiverJwe = new JsonWebEncryption();
// Set the compact serialization on new Json Web Encryption object
receiverJwe.setCompactSerialization(serializedJwe);
// Symmetric encryption, like we are doing here, requires that both parties have the same key.
// The key will have had to have been securely exchanged out-of-band somehow.
receiverJwe.setKey(new SecretKeySpec(digest, "AES"));
// Get the message that was encrypted in the JWE. This step performs the actual decryption steps.
String plaintext = receiverJwe.getPlaintextString();
// And do whatever you need to do with the clear text message.
System.out.println("plaintext: " + plaintext);
Let's assume you do indeed require AES in GCM mode (I've never heard of AGCM, but I guess this is a logical assumption that it means AES/GCM). Then the following could be used for (un)wrapping a secret key. Note that I didn't get this to work using IvParameterSpec, at least not for the Oracle JCE.
SecretKey sk = new SecretKeySpec(new byte[16], "AES");
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec gcmSpec = new GCMParameterSpec(128, new byte[12]);
cipher.init(Cipher.WRAP_MODE, sk, gcmSpec);
byte[] wrappedKey = cipher.wrap(sk);
System.out.println(Hex.toHexString(wrappedKey));
cipher.init(Cipher.UNWRAP_MODE, sk, gcmSpec);
SecretKey unwrap = (SecretKey) cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
System.out.println(Hex.toHexString(unwrap.getEncoded()));
Note that using SIV mode should probably be somewhat preferred for wrapping keys as you do do not require to store an IV and authentication tag together with the wrapped key (storing the IV is not shown in the example). The above code relies on a unique IV for security (also not shown).
Obviously it's also not a good idea to wrap a key with itself. Sorry, I got a bit lazy here; I've just shown how to use the cipher.
The "KW" refers to "key wrapping," as defined in RFC 3394. The name for this algorithm in the JCE is "AESWrap". So, the transformation should be "AESWrap/GCM/NoPadding". As Maarten pointed out, logically this operation should configure the Cipher in WRAP_MODE.

Java BadPaddingException "Given final block not properly padded" after several hours

Like many others over time I'm having issues with encryption in a system I'm maintaining.
Process A generates some encrypted text which later Process B must decode. They share the same code for this purpose which is as below:
public class DesEncryption {
private Cipher mEcipher;
private Cipher mDcipher;
private byte[] salt = {
(byte) 0x08, (byte) 0x90, (byte) 0xA6, (byte) 0x4B,
(byte) 0xBB, (byte) 0x51, (byte) 0x3C, (byte) 0xDE
};
// Iteration count
int iterationCount = 19;
DesEncryption(String passPhrase) throws EncryptionException {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
mEcipher = Cipher.getInstance(key.getAlgorithm());
mDcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
mEcipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
mDcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
throw new EncryptionException(e);
} catch (java.security.spec.InvalidKeySpecException e) {
throw new EncryptionException(e);
} catch (javax.crypto.NoSuchPaddingException e) {
throw new EncryptionException(e);
} catch (java.security.NoSuchAlgorithmException e) {
throw new EncryptionException(e);
} catch (java.security.InvalidKeyException e) {
throw new EncryptionException(e);
}
}
public String encrypt(String str) throws EncryptionException {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = mEcipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
throw new EncryptionException(e);
} catch (IllegalBlockSizeException e) {
throw new EncryptionException(e);
} catch (UnsupportedEncodingException e) {
throw new EncryptionException(e);
} catch (java.io.IOException e) {
throw new EncryptionException(e);
}
}
public String decrypt(String str) throws EncryptionException {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = mDcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
throw new EncryptionException(e);
} catch (IllegalBlockSizeException e) {
throw new EncryptionException(e);
} catch (UnsupportedEncodingException e) {
throw new EncryptionException(e);
} catch (java.io.IOException e) {
throw new EncryptionException(e);
}
}
}
The two processes run on separate servers, both Centos (5.3 for process A, 6.4 for Process B)
There are no apparent issues with Process A - The string to be encoded is done so reliably.
When process B starts, everything appears to be fine. It decodes and decrypts the required strings correctly.
At some point over the course of about 24 hours however, this stops working. At this point, I get the 'BadPaddingException "Given final block not properly padded"' Exceptions. This then continues every time the code is executed with any encoded string until such time as the process is restarted, at which point everything works again, including decoding strings that failed moments before.
At the time when this goes wrong, calling decrypt(encrypt("test")) will fail too so this seems to be unrelated to the actual encrypted value and more to do with the encryption and decryption getting out of sync some how.
If anyone could offer any suggestions about where I may be going wrong with this I'd appreciate it.
Many thanks in advance...
Andrew

python AES encryption java decryption

I have over 1000 images and videos that need to be encrypted. Nothing over the top just something simple, I was thinking of using AES but what I cannot figure out is how to encrypt on my computer then decrypt the item on the device.
I will be encrypting all the items on my computer probably using python. Then in an on demand fashion will decrypt the item with java (Android app)
Any simple explanation will do pseudo code is fine too.
The main issue im having is how to use the same key to encrypt and decrypt. I've been generating the key and can't get it to port to the other device for decryption.
Thanks
Python Code. Works encrypts and decrypts.
from Crypto.Cipher import AES
import os, random, struct
key = '0123456789abcdef'
mode = AES.MODE_CBC
chunksize = 64*1024
iv = ''.join(chr(random.randint(0,0xFF)) for i in range(16))
encryptor = AES.new(key,mode,iv)
filesize = os.path.getsize('sample.jpg')
with open('sample.jpg','rb') as infile:
with open('sample.enc','wb') as outfile:
outfile.write(struct.pack('<Q',filesize))
outfile.write(iv)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += ' ' * (16 - len(chunk) % 16)
outfile.write(encryptor.encrypt(chunk))
## decrypt
with open('sample.enc', 'rb') as infile:
origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
iv = infile.read(16)
decryptor = AES.new(key, AES.MODE_CBC, iv)
with open('sample2.jpg', 'wb') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(origsize)
How would I do the decrypt part in Java? Here is my quick sloppy java code that doesn't work. I think it is the padding that is messing it up.
public void decryptFile(){
String inFile = "sample.enc";
String outFile = "sample.jpg";
String dir = Environment.getExternalStorageDirectory() +"/Android/data/HOT/";
InputStream is ;
byte[] iv = new byte[16];
try {
is = new FileInputStream(dir+inFile);
is.read(iv);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
Log.d("D1","no file found");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("D-2","no file found");
e.printStackTrace();
}
byte[] k = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
Key key = new SecretKeySpec(k,"AES");
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(iv));
OutputStream outs = new FileOutputStream(dir+outFile);
is = new FileInputStream(dir+inFile);
while(true){
byte[] chunk = new byte[64*1024];
is.read(chunk);
if(chunk.length == 0){
break;
}
outs.write(cipher.doFinal(chunk));
}
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
Log.d("D","1");
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
Log.d("D","2");
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
Log.d("D","3");
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
Log.d("D","4");
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.d("D","5");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("D","6");
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
Log.d("D","7");
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
Log.d("D","8");
e.printStackTrace();
}
ImageView im = (ImageView)findViewById(R.id.imageView2);
Bitmap mainBitmap = BitmapFactory.decodeFile(dir+outFile);
im.setImageBitmap(mainBitmap);
}
In the Java version, you don't seem to be reading in the filesize before reading in the IV, unlike the Python version.
You also open a second FileInputStream and then don't skip the filesize and IV before reading in chunks for the Cipher.
Another thing to check is that the keys are being interpreted the same in Java and Python, i.e. the string in Python results in the same sequence of bytes as the byte array in Java.

Encrypt and decrypt with AES and Base64 encoding

I have following program for encrypting data.
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Test {
private static final String ALGORITHM = "AES";
private static final byte[] keyValue = "ADBSJHJS12547896".getBytes();
public static void main(String args[]) throws Exception {
String encriptValue = encrypt("dude5");
decrypt(encriptValue);
}
/**
* #param args
* #throws Exception
*/
public static String encrypt(String valueToEnc) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
System.out.println("valueToEnc.getBytes().length "+valueToEnc.getBytes().length);
byte[] encValue = c.doFinal(valueToEnc.getBytes());
System.out.println("encValue length" + encValue.length);
byte[] encryptedByteValue = new Base64().encode(encValue);
String encryptedValue = encryptedByteValue.toString();
System.out.println("encryptedValue " + encryptedValue);
return encryptedValue;
}
public static String decrypt(String encryptedValue) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
byte[] enctVal = c.doFinal(encryptedValue.getBytes());
System.out.println("enctVal length " + enctVal.length);
byte[] decordedValue = new Base64().decode(enctVal);
return decordedValue.toString();
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGORITHM);
return key;
}
}
Here I am getting the following out put with exception?
valueToEnc.getBytes().length 5
encValue length16
encryptedValue [B#aa9835
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
Can some one explain me the cause? Why its only saying when decrypting that length should be 16. Doesn't it convert to 16 as like encrypting with the doFinal method.
And as the exception says "how to decrypting without padded cipher?"
Your Order for encrypt: getBytes, encrypt, encode, toString
Your Order for decrypt(Wrong*): getBytes, decrypt, decode, toString
Two problems:
As someone already mentioned you should reverse the order of operations for decryption. You are not doing that.
encrypt gives you 16 bytes, encode 24 bytes, but toString gives 106 bytes. Something to do with invalid chars taking up additional space.
Note: Also, you don't need to call generateKey() twice.
Fix problem #1 by using the reverse order for decryption.
Correct order for decrypt: getBytes, decode, decrypt, toString
Fix problem #2 by replacing xxx.toString() with new String(xxx). Do this in both the encrypt and decrypt functions.
Your decrypt should look like this:
c.init(Cipher.DECRYPT_MODE, key)
val decodedValue = new Base64().decode(encryptedValue.getBytes())
val decryptedVal = c.doFinal(decodedValue)
return new String(decryptedVal)
This should give you back "dude5"
The line
String encryptedValue = encryptedByteValue.toString();
is the problem. The type of encryptedByteValue is byte[] and calling toString on it isn't what you want to do there. Instead try
String encryptedValue = Base64.getEncoder().encodeToString(encValue);
Then use Base64.decodeBase64(encryptedValue) in decrypt. You must do that prior to attempting to decrypt though. You must undo the operations in the reverse order of the encrypt method.
Fundamentally, there is an asymmetry between your encrypt function and your decrypt function. When you encrypt you perform an AES encrypt and then a base64 encode, when you decrypt you don't first undo the base64 encoding step.
I think that there's something wrong with your base64 encoding as well as [ shouldn't appear in a base64 encoded string.
Looking at the documentation for org.apache.commons.codec.binary.Base64 you should be able to do this on encode:
String encryptedValue = Base64.encodeBase64String(encValue);
and this on decode:
byte[] encValue = Base64.decodeBase64(encryptedValue);
Where are you getting a version of apache codec that has encodeToString or encodeBase64String?
I downloaded 1.5 from the apache site and while it says in the documentation that these methods exist, they don't show up when you do code completion and they create an unknown method when you provide them.
I was able to do:
byte raw[] = md.digest(); //step 4
byte hashBytes[] = Base64.encodeBase64(raw); //step 5
StringBuffer buffer = new StringBuffer();
for( int i=0; i<hashBytes.length; i++ )
buffer.append(hashBytes[i]);
return buffer.toString(); //step 6
And then the string that I obtained was very long, BUT it decrypted correctly.
I don't think this is the "right" way to do things, but can't find the methods that the documentation says are there.
That was alright, you just needed to
1) Use new String instead of toString() since toString() doesn't return what you need here (in both cases, encryption and decryption)
2) you need to decode first since the value is encode in base64.
I came across this thread but it took sometime to find out the actual point..I am posting my code for rest of the people who come across this issue.
public abstract class EncryptionDecryption {
static byte[] key = "!##$!##$%^&**&^%".getBytes();
final static String algorithm="AES";
public static String encrypt(String data){
byte[] dataToSend = data.getBytes();
Cipher c = null;
try {
c = Cipher.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SecretKeySpec k = new SecretKeySpec(key, algorithm);
try {
c.init(Cipher.ENCRYPT_MODE, k);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encryptedData = "".getBytes();
try {
encryptedData = c.doFinal(dataToSend);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encryptedByteValue = new Base64().encode(encryptedData);
return new String(encryptedByteValue);//.toString();
}
public static String decrypt(String data){
byte[] encryptedData = new Base64().decode(data);
Cipher c = null;
try {
c = Cipher.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SecretKeySpec k =
new SecretKeySpec(key, algorithm);
try {
c.init(Cipher.DECRYPT_MODE, k);
} catch (InvalidKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] decrypted = null;
try {
decrypted = c.doFinal(encryptedData);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new String(decrypted);
}
public static void main(String[] args){
String password=EncryptionDecryption.encrypt("password123");
System.out.println(password);
System.out.println(EncryptionDecryption.decrypt(password));
}
}
I have replaces line in example:
String encryptedValue = encryptedByteValue.toString();
with next one:
String encryptedValue = new String(encryptedByteValue);
All works fine!

Categories