return Base64.encodeBase64String(cipherText);
im getting an error in this line.It suggest me to make a class in base64,but is there any standard class for Base64?Im using this to encrypt.
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;
import java.io.*;
import java.lang.*;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class TRIPPLE_DES {
public static void main(String[] args) throws Exception {
String text = "cardNumber=28293939493330&securityCode=123&cardExpiryMonth=07&cardExpiryYear=2013&cardHolderName=Test&transactionAmount=50.00¤cyCode=356&customerReferenceNo=9393938393938&cardProvider=VISA&name=Test&mobileNo=983345123412&email=test#test.com&contactNo=983345123412&password=wyzgames&amount=100&remoteIP=10.10.10.50&checkSum=92be84d25b60b3f9f233c074d12ade1ddef158cb369a0734afff3fb6adc9d7ddb4b26f7e6001563747a8d47457e713750e5802b4871cfbe70baca9304d4c385f";
String codedtext = new TRIPPLE_DES().encrypt(text);
String decodedtext = new TRIPPLE_DES().decrypt(codedtext);
String encodedurl = URLEncoder.encode(codedtext,"UTF-8");
System.out.println(encodedurl);
System.out.println(decodedtext);
}
public String encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
return Base64.encodeBase64String(cipherText);
}
public String decrypt(String message) throws Exception
{
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] byteMessage= Base64.decodeBase64(message);
final byte[] plainText = decipher.doFinal(byteMessage);
return new String(plainText, "UTF-8");
}
}
There isn't an official Base64 class in JDK.
I can suggest you to use this: Apache Commons Codec
you can use Base64Encoder and Base64Decoder for you purpose.
Change
Base64.encodeBase64String(cipherText)
to
new BASE64Encoder().encode(cipherText)
and
Base64.decodeBase64(message)
to
new BASE64Decoder().decodeBuffer(message)
Related
I would like to encrypt this javascript code in android.
let base64Key = CryptoJS.enc.Base64.parse(key);
let encryptedValue = CryptoJS.AES.encrypt(value, base64Key, {
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
iv: base64Key
});
return encryptedValue.toString();
Code:
String encryptedKey = Base64.encodeToString(keyword.getBytes(), Base64.NO_WRAP);
Key key = new SecretKeySpec(encryptedKey.getBytes(), algorithm);
Cipher chiper = Cipher.getInstance("AES");
chiper.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = chiper.doFinal(plainText.getBytes());
String encryptedValue = Base64.encodeToString(encVal, Base64.NO_WRAP);
return encryptedValue;
But it returns a completely different value.
The first line of the code itself returns a different value in both cases:
So I got this part working.
I just needed to add the following lines to the android code:
byte[] decoded = Base64.decode(key.getBytes());
String hexString = Hex.encodeHexString(decoded);
This is the equivalent of CryptoJS.enc.Base64.parse(key); this line in CryptoJS.
But still trying to figure out the end result though. Both are different.
I am also having same issue but finally, i got a Class from Git.
AESHelper.decrypt("your secret key","encryptedText")
import com.sun.jersey.core.util.Base64;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESHelper {
/**
*
* Conforming with CryptoJS AES method
* **** YOU NEED TO ADD "JCE policy" to have ability to DEC/ENC 256 key-lenght with AES Cipher ****
*
*/
static int KEY_SIZE = 256;
static int IV_SIZE = 128;
static String HASH_CIPHER = "AES/CBC/PKCS7Padding";
static String AES = "AES";
static String CHARSET_TYPE = "UTF-8";
static String KDF_DIGEST = "MD5";
// Seriously crypto-js, what's wrong with you?
static String APPEND = "Salted__";
/**
* Encrypt
* #param password passphrase
* #param plainText plain string
*/
public static String encrypt(String password,String plainText) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
byte[] saltBytes = generateSalt(8);
byte[] key = new byte[KEY_SIZE/8];
byte[] iv = new byte[IV_SIZE/8];
EvpKDF(password.getBytes(CHARSET_TYPE), KEY_SIZE, IV_SIZE, saltBytes, key, iv);
SecretKey keyS = new SecretKeySpec(key, AES);
Cipher cipher = Cipher.getInstance(HASH_CIPHER);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, keyS, ivSpec);
byte[] cipherText = cipher.doFinal(plainText.getBytes(CHARSET_TYPE));
// Thanks kientux for this: https://gist.github.com/kientux/bb48259c6f2133e628ad
// Create CryptoJS-like encrypted !
byte[] sBytes = APPEND.getBytes(CHARSET_TYPE);
byte[] b = new byte[sBytes.length + saltBytes.length + cipherText.length];
System.arraycopy(sBytes, 0, b, 0, sBytes.length);
System.arraycopy(saltBytes, 0, b, sBytes.length, saltBytes.length);
System.arraycopy(cipherText, 0, b, sBytes.length + saltBytes.length, cipherText.length);
byte[] bEncode = Base64.encode(b);
return new String(bEncode);
}
/**
* Decrypt
* Thanks Artjom B. for this: http://stackoverflow.com/a/29152379/4405051
* #param password passphrase
* #param cipherText encrypted string
*/
public static String decrypt(String password,String cipherText) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
byte[] ctBytes = Base64.decode(cipherText.getBytes(CHARSET_TYPE));
byte[] saltBytes = Arrays.copyOfRange(ctBytes, 8, 16);
byte[] ciphertextBytes = Arrays.copyOfRange(ctBytes, 16, ctBytes.length);
byte[] key = new byte[KEY_SIZE/8];
byte[] iv = new byte[IV_SIZE/8];
EvpKDF(password.getBytes(CHARSET_TYPE), KEY_SIZE, IV_SIZE, saltBytes, key, iv);
Cipher cipher = Cipher.getInstance(HASH_CIPHER);
SecretKey keyS = new SecretKeySpec(key, AES);
cipher.init(Cipher.DECRYPT_MODE, keyS, new IvParameterSpec(iv));
byte[] plainText = cipher.doFinal(ciphertextBytes);
return new String(plainText);
}
private static byte[] EvpKDF(byte[] password, int keySize, int ivSize, byte[] salt, byte[] resultKey, byte[] resultIv) throws NoSuchAlgorithmException {
return EvpKDF(password, keySize, ivSize, salt, 1, KDF_DIGEST, resultKey, resultIv);
}
private static byte[] EvpKDF(byte[] password, int keySize, int ivSize, byte[] salt, int iterations, String hashAlgorithm, byte[] resultKey, byte[] resultIv) throws NoSuchAlgorithmException {
keySize = keySize / 32;
ivSize = ivSize / 32;
int targetKeySize = keySize + ivSize;
byte[] derivedBytes = new byte[targetKeySize * 4];
int numberOfDerivedWords = 0;
byte[] block = null;
MessageDigest hasher = MessageDigest.getInstance(hashAlgorithm);
while (numberOfDerivedWords < targetKeySize) {
if (block != null) {
hasher.update(block);
}
hasher.update(password);
block = hasher.digest(salt);
hasher.reset();
// Iterations
for (int i = 1; i < iterations; i++) {
block = hasher.digest(block);
hasher.reset();
}
System.arraycopy(block, 0, derivedBytes, numberOfDerivedWords * 4,
Math.min(block.length, (targetKeySize - numberOfDerivedWords) * 4));
numberOfDerivedWords += block.length/4;
}
System.arraycopy(derivedBytes, 0, resultKey, 0, keySize * 4);
System.arraycopy(derivedBytes, keySize * 4, resultIv, 0, ivSize * 4);
return derivedBytes; // key + iv
}
private static byte[] generateSalt(int length) {
Random r = new SecureRandom();
byte[] salt = new byte[length];
r.nextBytes(salt);
return salt;
}
}
Check out related question here and page on Java Cryptographic Extensions
To turn a text string (UTF-8 encoded) into a base-64 string, you need:
var textString = 'Hello world'; // Utf8-encoded string
var words = CryptoJS.enc.Utf8.parse(textString); // WordArray object
var base64 = CryptoJS.enc.Base64.stringify(words); // string: 'SGVsbG8gd29ybGQ='
Finally got it working in Android using the below code, if anyone else faces the issue:
public static String encrypt(String key, String value) {
try {
SecretKey secretKey = new SecretKeySpec(Base64.decode(key.getBytes(), Base64.NO_WRAP), "AES");
AlgorithmParameterSpec iv = new IvParameterSpec(Base64.decode(key.getBytes(), Base64.NO_WRAP));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return new String(Base64.encode(cipher.doFinal(value.getBytes("UTF-8")), Base64.NO_WRAP));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
The below code works for me,
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class EncryptionUtils {
private static final String key = "123456$##$^#RRRR";//16 characters
private static final String initVector = "123456$##$^#RRRR";//16 characters
public static String encrypt(String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
// byte[] finalCiphertext = new byte[encrypted.length+2*16];
return Base64.encodeToString(encrypted, Base64.NO_WRAP);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
We have an application running in .NET for several years. It uses the below c# code for encryption and decryption of password. Now we have another application in Java to consume the same DB for authentication. Tried various ways but could not get an equivalent code in Java for the below encryption and decryption in C#. As there are lot of data encrypted using this logic and stored in DB, will not be able change the C# code. Could someone help with equivalent code in Java? Thanks in Advance.
private string passphrase = "XYZ";
public string EncryptData(string Data)
{
byte[] Results;
var UTF8 = new UTF8Encoding();
var HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
var TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToEncrypt = UTF8.GetBytes(Data);
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
}
public string DecryptString(string Message)
{
byte[] Results;
var UTF8 = new UTF8Encoding();
var HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
var TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(Message.Replace(" ", "+"));
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
}
Tried Java Code
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class TripleDESTest {
public static void main(String[] args) throws Exception {
String text = "test";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext);
System.out.println(decodedtext);
}
public byte[] encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("XYZ"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
// final String encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(cipherText);
return cipherText;
}
public String decrypt(byte[] message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("XYZ"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
// final byte[] encData = new
// sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
}
It looks like the problem is not finding equivalent code, but to port your C# code to Java, but because of the C# references and .net assemblies used, to use equivalent Java libs that support Triple DES. Have you investigated equivalent Java libs for Triple Des? A quick search found this example:
https://www.example-code.com/java/crypt2_3des.asp
This is my first project in Java and I decided to make a simple text encryptor using AES.
The error I am getting is: The method init(int, Key) in the type Cipher is not applicable for the arguments (int, byte[])
Code:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Key;
import javax.crypto.*;
import java.util.*;
public class Encryptor {
public static void main(String[] args) throws Exception {
String FileName = "encryptedtext.txt";
String FileName2 = "decryptedtext.txt";
Scanner input = new Scanner(System.in);
System.out.println("Enter your 16 character key here:");
String EncryptionKey = input.next();
KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
KeyGen.init(128);
Cipher AesCipher = Cipher.getInstance("AES");
System.out.println("Enter text to encrypt or decrypt:");
String Text = input.next();
System.out.println("Do you want to encrypt or decrypt (e/d)");
String answer = input.next();
if (answer.equalsIgnoreCase("e")){
byte[] byteKey = (EncryptionKey.getBytes());
byte[] byteText = (Text).getBytes();
AesCipher.init(Cipher.ENCRYPT_MODE, byteKey); // ERROR LINE
byte[] byteCipherText = AesCipher.doFinal(byteText);
Files.write(Paths.get(FileName), byteCipherText);
}
else if (answer.equalsIgnoreCase("d")){
byte[] byteKey = (EncryptionKey.getBytes());
byte[] byteText = (Text).getBytes();
byte[] cipherText = Files.readAllBytes(Paths.get(FileName));
AesCipher.init(Cipher.DECRYPT_MODE, byteKey); // ERROR LINE
byte[] bytePlainText = AesCipher.doFinal(cipherText);
Files.write(Paths.get(FileName2), bytePlainText);
}
}
}
Thanks in advance! :)
This is Full code
Full code:
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
public class Encrypter {
public static void main(String[] args) throws Exception {
String FileName = "encryptedtext.txt";
String FileName2 = "decryptedtext.txt";
Scanner input = new Scanner(System.in);
System.out.println("Enter your 16 character key here:");
String EncryptionKey = input.next();
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
KeyGen.init(128);
Cipher AesCipher = Cipher.getInstance("AES/CFB/NoPadding");
System.out.println("Enter text to encrypt or decrypt:");
String Text = input.next();
System.out.println("Do you want to encrypt or decrypt (e/d)");
String answer = input.next();
if (answer.equalsIgnoreCase("e")){
byte[] byteKey = (EncryptionKey.getBytes());
byte[] byteText = (Text).getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,ivspec );
AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,ivspec); // ERROR LINE
byte[] byteCipherText = AesCipher.doFinal(byteText);
Files.write(Paths.get(FileName), byteCipherText);
}
else if (answer.equalsIgnoreCase("d")){
byte[] byteKey = (EncryptionKey.getBytes());
byte[] byteText = (Text).getBytes();
byte[] cipherText = Files.readAllBytes(Paths.get(FileName));
SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
AesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec,ivspec); // ERROR LINE
byte[] bytePlainText = AesCipher.doFinal(cipherText);
Files.write(Paths.get(FileName2), bytePlainText);
}
}
}
You should not pass byte array directly to Cipher object, instead you need to create object of SecretKeySpecs.
This is complete Code
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
public class Encrypter {
public static void main(String[] args) throws Exception {
String FileName = "encryptedtext.txt";
String FileName2 = "decryptedtext.txt";
Scanner input = new Scanner(System.in);
System.out.println("Enter your 16 character key here:");
String EncryptionKey = input.next();
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
KeyGen.init(128);
Cipher AesCipher = Cipher.getInstance("AES/CFB/NoPadding");
System.out.println("Enter text to encrypt or decrypt:");
String Text = input.next();
System.out.println("Do you want to encrypt or decrypt (e/d)");
String answer = input.next();
if (answer.equalsIgnoreCase("e")) {
byte[] byteKey = (EncryptionKey.getBytes());
byte[] byteText = (Text).getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
byte[] byteCipherText = AesCipher.doFinal(byteText);
Files.write(Paths.get(FileName), byteCipherText);
} else if (answer.equalsIgnoreCase("d")) {
byte[] byteKey = (EncryptionKey.getBytes());
byte[] byteText = (Text).getBytes();
byte[] cipherText = Files.readAllBytes(Paths.get(FileName));
SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
AesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
byte[] bytePlainText = AesCipher.doFinal(cipherText);
Files.write(Paths.get(FileName2), bytePlainText);
}
}
}
I had to encrypt a URL for been exposed in a external link, and I have created a class to encrypt on AES. Maybe this can help someone.
I added a method to create my Random Initial Vector and it is on this class also.
package br.com.tokiomarine.captcha.encryption;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.text.CharacterPredicates;
import org.apache.commons.text.RandomStringGenerator;
public class Encryptor
{
public static String encrypt(String key, String initVector, String value) throws Exception
{
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
return Base64.encodeBase64URLSafeString(encrypted);
}
public static String decrypt(String key, String initVector, String encrypted) throws Exception
{
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
}
public static String generateInitVector() {
RandomStringGenerator randomStringGenerator =
new RandomStringGenerator.Builder()
.withinRange('0', 'z')
.filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
.build();
return randomStringGenerator.generate(16);
}
}
And here is my Test Class:
public class EcryptionTest {
#Test
public void encryptionTest() {
try
{
String key = "Key#TokioMarineC";
for(int i = 0; i < 1000; i++)
{
String initVector = Encryptor.generateInitVector();
String encrypted = Encryptor.encrypt(key, initVector, "StringTeste");
assertTrue("StringTeste".equals(Encryptor.decrypt(key, initVector, encrypted)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'm trying to do an Encryption and Decryption in Java Android.
Below is my code for C#, I need to convert it to Java Android. Can someone help me how to do it?
I've been doing this for almost 2 days yet can't find any solutions on how to convert it. I'm newbie in Android.
public static string Encrypt(string toEncrypt)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
string key = "KEY";
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string cipherString)
{
try
{
byte[] keyArray;
byte[] toEncryptArray = Convert.FromBase64String(cipherString);
string key = "KEY";
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
catch (Exception)
{
return "Invalid";
}
}
Try This,
package mypackage;
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Main {
public static void main(String[] args) throws Exception {
String text = "neeraj";
String codedtext = new Main().encrypt(text);
String decodedtext = new Main().decrypt(codedtext);
System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
System.out.println(decodedtext); // This correctly shows "neeraj"
}
public String encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("KEY"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
// final String encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(cipherText);
return Base64.encodeBase64String(cipherText);
}
public String decrypt(String input) throws Exception {
byte[] message = Base64.decodeBase64(input);
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("KEY"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DES/ECB/PKCS7Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
// final byte[] encData = new
// sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
}
Refer to the main function for usage.
I have updated my code. Your C# program gives output as a base64 string. But in java the input of decrypt and output of encrypt is byte array. Convert the byte array to base64 and it will work.
For Base64 operation in java you need the Apache Commons codec.
In java 8 you can use java.util.Base64
I am new to Security in java.
I have two clear double length keys which was used for generating ZPK (under LMK) in Futurex HSM.
Below mentioned pin blocks were encrypted using ZPK.
Is there a way to decrypt the block using clear keys in java.
clear_1 = "801CB5C89DC416C149FB645BB36897AD"
clear_2 = "45B98FC7D33149E0512F0ED9135E5826"
encrypted_pin_block = "6288FA9534BF2AA3"
encrypted_pin_block = "B8D876F238348EB0"
Decrypted value for one of these encrypted blocks is 2222.
See Sample Example for 3dec encryption and decryption
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
class ZiggyTest2{
public static void main(String[] args) throws Exception{
String text = "I am sunil";
byte[] codedtext = new ZiggyTest2().encrypt(text);
String decodedtext = new ZiggyTest2().decrypt(codedtext);
System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
System.out.println(decodedtext); // This correctly shows "kyle boon"
}
public byte[] encrypt(String message) throws Exception {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digestOfPassword = md.digest("ABCDEABCDE"
.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] plainTextBytes = message.getBytes("utf-8");
byte[] cipherText = cipher.doFinal(plainTextBytes);
// String encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(cipherText);
return cipherText;
}
public String decrypt(byte[] message) throws Exception {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digestOfPassword = md.digest("ABCDEABCDE"
.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
}