TripleDES encrypting with vb.net and decrypting with java - java

I'm creating an interface for two applications that will communicate using encrypted text in .txt files. vb.net app will encrypt and java will decrypt.
vb code
Dim nget As String = System.IO.File.ReadAllText(sInputFilename)
Dim textBytes As Byte() = System.Text.Encoding.Unicode.GetBytes(nget)
Dim Passphrase As String = sKey
Dim UTF8 As New System.Text.UTF8Encoding()
Dim HashProvider As New MD5CryptoServiceProvider()
Dim TDESKey As Byte() = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase))
Dim TDESAlgorithm As New TripleDESCryptoServiceProvider()
TDESAlgorithm.Key = TDESKey
TDESAlgorithm.Mode = CipherMode.ECB
TDESAlgorithm.Padding = PaddingMode.PKCS7
Dim ms As New System.IO.MemoryStream()
Dim encStream As New CryptoStream(ms, TDESAlgorithm.CreateEncryptor(), CryptoStreamMode.Write)
encStream.Write(textBytes, 0, textBytes.Length)
encStream.FlushFinalBlock()
Dim strSave As String = Convert.ToBase64String(ms.ToArray())
My.Computer.FileSystem.WriteAllText(sOutputFilename, strSave, False)
java code
public static void main(String[] args) {
String codedtext = null;
try {
codedtext = readFile("ect.txt", StandardCharsets.UTF_8);
} catch (IOException e1) {
e1.printStackTrace();
}
String decodedtext = null;
try {
decodedtext = _decrypt(codedtext,"abcdefgh");
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
private static String _encrypt(String message, String secretKey) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainTextBytes = message.getBytes("utf-8");
byte[] buf = cipher.doFinal(plainTextBytes);
byte [] base64Bytes = Base64.encodeBase64(buf);
String base64EncryptedString = new String(base64Bytes);
return base64EncryptedString;
}
private static String _decrypt(String encryptedText, String secretKey) throws Exception {
byte[] message = Base64.decodeBase64(encryptedText.getBytes("utf-8"));
//byte[] message = encryptedText.getBytes("utf-8");
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
//Cipher decipher = Cipher.getInstance("DESede");
Cipher decipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
but I'm getting the error
at java.lang.ArrayIndexOutOfBoundsException: -17
at org.apache.commons.codec.binary.Base64.isBase64(Base64.java:137)
at org.apache.commons.codec.binary.Base64.discardNonBase64(Base64.java:478)
at org.apache.commons.codec.binary.Base64.decodeBase64(Base64.java:374)
at Test.MyDec._decrypt(MyDec.java:74)
at Test.MyDec.main(MyDec.java:33)
when decoding from base64

Related

DESede-ECB Encryption-Decryption

I'm trying to Encrypt and decrypt a string in java using the following code:
public byte[] encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("MYKEY12345"
.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);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
// final String encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(cipherText);
Log.d("base64", Base64.getEncoder().encodeToString(cipherText));
return cipherText;
}
public String decrypt(byte[] message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("MYKEY12345"
.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);
// final byte[] encData = new
// sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
usage:
byte[] codedtext = new Common().encrypt("HELLOWORLD!"); // Function to get the Encrption
Output:
base64: Ya9zBTukyOmdOh5/5vCaGA== // encrypted string converted to base64
Encrypted : [B#d41c149
ToDecrypt:
String decodedtext = new Common().decrypt(codedtext); // To decrypt String
Output:
Decrypted : HELLOWORLD! // from Encrypted string
Now if i use the same Key and String to get the encryption key online i get different values.
Using this link to verify my encryption/decryption.
I'm just starting in encryption/decryption so any help is appreciated about any thing that i'm doing wrong here.
You need
final byte[] plainText = decipher.doFinal(Base64.getDecoder().decode(message));

AES+ Base64 Decrypt file appeared garbled

I am using socket to transfer file and AES 256 to encrypt/decrypt, I use the byte array to accept file's content and encrypt it, but only the first byte size array success to decrypt and other appeared garbled(the encrypted byte size extend to 1368 and AES block size is 128bits not sure is it effect),below is my code:
public void sendfile() {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
byte[] byteArray = new byte[1024];
int bytesCount = 0;
while ((bytesCount = fis.read(byteArray)) >= 0) {
String encryptString = new String(byteArray, "UTF-8");
bos.write(EncryptAES.encrypt(encryptString, "12345").getBytes("UTF-8"));
}
}
public void receiveFile(File file, BufferedInputStream bis) {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
byte[] byteArray = new byte[1024];
int bytesCount = 0;
while ((bytesCount = bis.read(byteArray)) >= 0) {
String encryptString = new String(byteArray, "UTF-8");
bos.write(EncryptAES.decrypt(encryptString, "12345").getBytes("UTF-8"));
}
}
public static String encrypt(String content,SecretKey secretKey) {
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] byteContent = cipher.doFinal(content.getBytes("UTF-8"));
return Base64.getEncoder().withoutPadding().encodeToString(byteContent);
}
public static String decrypt(String content,SecretKey secretKey) {
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] byteCipherText = Base64.getDecoder().decode(content);
String encryptString = new String(byteCipherText, "UTF-8");
byte[] decryptedText = cipher.doFinal(byteCipherText);
encryptString = new String(decryptedText, "UTF-8");
return new String(decryptedText, "UTF-8");
}

Require an equivalent code in Java from C# for encryption and decryption

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

C# to Java TripleDES , different results

I'm attempting to convert this C# encryption algorithm to Java; however, I keep retrieving slightly different encrypted results (haven't tried decryption yet). It may also be important to point out that I'm not able to change the C# code.
However when I call the encrypt function in C# on the string "test" it will return nmj8MjjO52y928Syqf0J+g== However in Java it'll return C6xyQjJCqVo=
The C#
private static String key = "012345678901234567890123";
public static string encrypt(String stringToEncrypt)
{
TripleDES des = CreateDES(key);
ICryptoTransform ct = des.CreateEncryptor();
byte[] input = Encoding.Unicode.GetBytes(stringToEncrypt);
byte[] output = ct.TransformFinalBlock(input, 0, input.Length);
//return output;
return Convert.ToBase64String(output);
}
public static String decrypt(string encryptedString)
{
byte[] input = Convert.FromBase64String(encryptedString);
TripleDES des = CreateDES(key);
ICryptoTransform ct = des.CreateDecryptor();
byte[] output = ct.TransformFinalBlock(input, 0, input.Length);
return Encoding.Unicode.GetString(output);
}
public static TripleDES CreateDES(string key)
{
MD5 md5 = new MD5CryptoServiceProvider();
TripleDES des = new TripleDESCryptoServiceProvider();
des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));
des.IV = new byte[des.BlockSize / 8];
return des;
}
My Attempt with converting to Java
private static String key = "012345678901234567890123";
public static void main(String[] args) throws Exception {
String text = "test";
String codedtext = encrypt(text);
//String decodedtext = decrypt(codedtext);
System.out.println(new String(codedtext));
//System.out.println(decodedtext);
}
public static String encrypt(String message) throws Exception {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digestOfPassword = md.digest(key.getBytes("unicode"));
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();
byte[] cipherText = cipher.doFinal(plainTextBytes);
String output = Base64.encode(cipherText);
return output;
}
public static String decrypt(String message) throws Exception {
byte[] messageBytes = Base64.decode(message);
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digestOfPassword = md.digest(key.getBytes());
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(messageBytes);
return new String(plainText);
}
Does anyone see what I'm overseeing?
You are missing two things. You are using a 16 length key on the c# side since it is not padded like the Java version. By default if the key is 16 bytes in length it will be padded with the first 8 bytes of the key.
To make this match on the Java side you will have to uncomment that line that adds the padding to the key:
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
SecretKey secretKey = new SecretKeySpec(keyBytes, 0, 24, "DESede");
Also, on the java side there was a suggestion to make sure to use UTF-LE for the text. Make sure to use it for everything. So the lines:
byte[] digestOfPassword = md.digest(key.getBytes("UTF-16LE"));
byte[] plainTextBytes = clearText.getBytes("UTF-16LE");
In general I would make sure to set the c# params of all the tripledes object, and not depend on defaults.
Here are two versions that match in c# and java
Java
String key = "012345678901234567890123";
String clearText = "test";
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digestOfPassword = md.digest(key.getBytes("UTF-16LE"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
String byteText = Arrays.toString(keyBytes);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
SecretKey secretKey = new SecretKeySpec(keyBytes, 0, 24, "DESede");
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] plainTextBytes = clearText.getBytes("UTF-16LE");
byte[] cipherText = cipher.doFinal(plainTextBytes);
String output = Base64.encode(cipherText);
c#
string clearText = "test";
string key = "012345678901234567890123";
string encryptedText = "";
MD5 md5 = new MD5CryptoServiceProvider();
TripleDES des = new TripleDESCryptoServiceProvider();
des.KeySize = 128;
des.Mode = CipherMode.CBC;
des.Padding = PaddingMode.PKCS7;
byte[] md5Bytes = md5.ComputeHash(Encoding.Unicode.GetBytes(key));
byte[] ivBytes = new byte[8];
des.Key = md5Bytes;
des.IV = ivBytes;
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
ICryptoTransform ct = des.CreateEncryptor();
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
encryptedText = Convert.ToBase64String(ms.ToArray());
}
Edited: Both versions now return the test case result "nmj8MjjO52y928Syqf0J+g=="

C# to Java Encryption and Decryption

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

Categories