I need to do triple DES encryption in GWT client file and need to do decryption of encrypted string in javascript. I have used TripleDesCipher in GWT but while doing decryption in javascript using crypto-js, I am getting blank string. Following is my GWT code.
TripleDesCipher cipher = new TripleDesCipher();
String enc ="";
String key = "579D2D852F2F3BABABBD71B7";
cipher.setKey(key.getBytes());
try {
enc = cipher.encrypt(String.valueOf(value));
} catch (DataLengthException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (InvalidCipherTextException e1) {
e1.printStackTrace();
}
Following is my javascript code for decryption.
var encrypted = urlParams.get('id');
var base64String = encrypted.toString();
alert(base64String);
var key = "579D2D852F2F3BABABBD71B";
var decrypted =
CryptoJS.TripleDES.decrypt(base64String,key);
console.log("DES3 decrypted text:"+ decrypted.toString(CryptoJS.enc.Utf8));
Related
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.
I am going to integrate two web applications written in different platforms (Java and Ruby),
I have to use common encryption algorithm for password in both application.
Is there any common encryption/decryption algorithm for both? If yes, please mention any useful link or any example.
It would be highly appreciated. Thanks in advance
In addition during my digging out it I found,
I have used Base64 with DES in both, interesting thing is that Characters and special characters give me same result in both but as i adding any number like (1,2,3), half of result is same and half encryption is something different.
*Ruby Code
require 'openssl'
require 'base64'
c = OpenSSL::Cipher::Cipher.new("des")
c.encrypt
c.key ="REPPIFY_ABCDEFGHIJKLMNOPQRSTUVWXYZ"
e = c.update("ankit#123")
e << c.final
puts Base64.encode64(e)
Output: Cbe9GslMs8mh33jAOD9qsw==
*Java Code
I am defining only encryption method here:-
public static String encryptPassword(String pass) {
public static final String DESKEY = "REPPIFY_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("Here is my password = "+pass);
DESKeySpec keySpec = null;
SecretKeyFactory keyFactory = null;
SecretKey key = null;
Cipher cipher = null;
BASE64Encoder base64encoder = new BASE64Encoder();
byte[] cleartext = null;
String encrypedPwd = null;
String pass = "ankit#123";
try {
keySpec = new DESKeySpec(DESKEY.getBytes("UTF8"));
keyFactory = SecretKeyFactory.getInstance("DES");
key = keyFactory.generateSecret(keySpec);
if(pass!=null) {
cleartext = pass.getBytes("UTF8");
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
encrypedPwd = base64encoder.encode(cipher.doFinal(cleartext));
}
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} // cipher is not thread safe
catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
System.out.println("Here I am printing encrypted pwd = "+encrypedPwd);
return encrypedPwd;
}
Output in Java :- Cbe9GslMs8mWn9yTmZrUiw==
Well, in the Ruby world, I'd recommend BCrypt, which is also favored by popular authentication plugins like Devise. I'm not very familiar with Java but a quick search suggests that there's BCrypt implementation in Java too:
http://www.mindrot.org/projects/jBCrypt/
EDIT - BCrypt is 1-way encryption, mainly for use in hashing passwords. If you are looking for something that will encrypt and decrypt then you'll have to look at something else. Seeing as you mentioned it's for passwords I'd suggest you only want 1-way encryption though.
I got the answer...just change a following line in ruby code and then you can use base64 decoder with DES in both:
c = OpenSSL::Cipher::Cipher.new("DES-ECB")
require 'openssl'
require 'base64'
c = OpenSSL::Cipher::Cipher.new("DES-ECB")
c.encrypt
c.key ="REPPIFY_ABCDEFGHIJKLMNOPQRSTUVWXYZ"
e = c.update("ankit#123")
e << c.final
puts Base64.encode64(e)
i am using android to create a key pair, i use http post to send the public key to a wamp server mysql data base using a php script.
after successfully receiving the key, the php scripts encrypts a string using the key and encoding it with base43, the sripts echos a json object to android.....where i decode using base64 and then use the private key to decrypt the text and then base64encode it again to view it.
php
$rawKey = $_POST['rawKey'];
$publicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" . chunk_split($rawKey) .
"-----END RSA PUBLIC KEY-----";
$rsa = new Crypt_RSA();
$rsa->loadKey($publicKey); // public key
$AESKeyString = "some text";
$AESKeyString = $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($AESKeyString);
$ciphertext = base64_encode($ciphertext);
$response = array('' => $ciphertext);
echo json_encode($response);
java
public String Decrypt(String encryptedKey) {
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
} 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, privKey);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] cipherData = null;
try {
cipherData = cipher.doFinal(Base64.decode(encryptedKey, Base64.NO_WRAP));
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String cipherString = Base64.encodeToString(cipherData, Base64.NO_WRAP);
Log.d("SecCom", cipherString);
return cipherString;
}
the problem WAS that although there were no errors in decryption the text was always garbage....however this garbage was unique and same for a give plaintext....that is to say "hello world" in java would always translate to "n;lk#;la" and only changing the plain text would change the decrypted garbage.
i looked at numerous examples on stackoverflow and this seemed to work for them and purely out of some gut feeling i added a base64 decode to the php string before encrypting it
$AESKeyString = base64_decode("some text");
and viola this solved the problem except for the fact that now i get origional string in java except that all the spaces are removed..... and the last character is replaced by g==
that is "some text" appears as "sometexg=="
i have tried numerous texts but this is constant through all no spaces and last character replaced by g==
in my final php script i will be generating random bytes for aes, encrypting them and then encoding them to send to java. please keep this in mind in the solution that you provide me.....
also why did adding base64.decode in php was necessary for me yet for others it worked just out of the box
thanks
as i mentioned in my comments.... my problem was not understanding the String and encoding part and how it tranlates to java.....
well i gave it a go, did a bit of reading and rewrote the php side and it worked in the first attempt.....
.... here is a full working php code....the java code does not need to be changed....i have also commented it
php
//get the posted public key
$pumpumString = $_POST['pumpum'];
//format public key in CRYPT format
$publicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" . chunk_split($pumpumString) .
"-----END RSA PUBLIC KEY-----";
//initialise Algorithm
$rsa = new Crypt_RSA();
$rsa->loadKey($publicKey); // public key
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
//generate new AES Session Key
$AESKey = rand_sha1(32); //a custom created function
$AESKeyDecoded = base64_decode($AESKey);
//encrypt AES Session Key
$ciphertext = $rsa->encrypt($AESKeyDecoded);
//base 64 encode it for transfer over internet
$ciphertextEncoded = base64_encode($ciphertext);
//prepare array for sending to client
$response = array('plum' => $ciphertextEncoded);
//write the encoded and decoded AES Session Key to file for comparison
$file = fopen('key.txt', 'w');
fwrite($file, "\n". $AESKey);
//echo JSON
echo json_encode($response);
one of the things that puzzled me earlier was why i needed to base64 decode my plaintext before encryption....well what i have been able to figure out is that, php probably uses ASCII to store strings. since in java i am using a base64_encode to get the decrypted string from the decrypted byte array.....i need to first decode my ascii plaintext string to regenerate it in java......(i might have worded that a bit non-coherently...please feel free to reword it.)
if u feel that i have come to the wrong conclusion or something can be bettered please let me know, i am marking this as solved....
also i had asked for a way to generate a random aes key.....below is the function i used to do it.....courtesy https://stackoverflow.com/a/637322/2208279
php
function rand_sha1($length) {
$max = ceil($length / 40);
$random = '';
for ($i = 0; $i < $max; $i ++) {
$random .= sha1(microtime(true).mt_rand(10000,90000));
}
return substr($random, 0, $length);
}
i am using a aes256 so i have used 32 as the argument to this function....modify it to 16 for 128
thanks....hope this helps someone.
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.
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!