I have a different result between java and php method in doing AES128 with zero padding and no IV encryption.
Here PHP code :
<?php
$ptaDataString = "secretdata";
$ptaDataString = encryptData($ptaDataString);
$ptaDataString = base64_encode($ptaDataString);
function encryptData($input) {
$ptaKey = 'secret';
$iv = "\0";
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $ptaKey, $input, MCRYPT_MODE_CBC, $iv);
return $encrypted;
}
echo $ptaDataString;
?>
And here is java code:
public static String encrypt() throws Exception {
try {
String data = "secretdata";
String key = "secret0000000000";
String iv = "0000000000000000";
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return new sun.misc.BASE64Encoder().encode(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
php resulting : kjgE5p/3qrum6ghdjiVIoA==
Java resulting : zLKhVMksRRr1VHQigmPQ2Q==
Any help would be appreciated,
Thanks
In Java, a zero byte expressed as a string is "\0" not "0". If you correct your example as follows, the results match:
String data = "secretdata";
String key = "secret\0\0\0\0\0\0\0\0\0\0";
String iv = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
In the case of the IV, it's probably just easier to write:
byte[] iv = new byte[<block size>];
In the final line of your code, you access sun.misc.BASE64Encoder(). Accessing anything that starts with sun.* is frowned upon, since these are internal classes. Consider instead using:
return DatatypeConverter.printBase64Binary(encrypted);
Related
I am trying to covert a c# encryption method to java. It is Triple DES with MD5 hash in ECB mode and I am having a hard time finding the java equivalent. The hashes do not match when I try to run them
Below is the c# code
public string Encrypt(string value, string key)
{
string encrypted;
var hashmd5 = new MD5CryptoServiceProvider();
var des = new TripleDESCryptoServiceProvider();
des.Key = hashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
des.Mode = CipherMode.ECB; //CBC, CFB
var buff = ASCIIEncoding.ASCII.GetBytes(value);
encrypted = Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buff, 0, buff.Length));
return encrypted;
}
Here is the Java Code
public String encryptSession (String session, String sessionEncryptionKey) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = EncodingUtils.getAsciiBytes(sessionEncryptionKey);
byte[] digestOfPassword = md.digest(hash);
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] sessionBytes = EncodingUtils.getAsciiBytes(session);
byte[] buf = cipher.doFinal(sessionBytes);
byte[] base64Bytes = Base64.getEncoder().encode(buf);
String base64EncryptedString = new String(base64Bytes);
return base64EncryptedString;
}
I have got this code from Server guys:
public string Encryption(string PlainText)
{
string key = "twelve_digit_key";
TripleDES des = CreateDES(key);
ICryptoTransform ct = des.CreateEncryptor();
byte[] input = Encoding.Unicode.GetBytes(PlainText);
byte[] buffer = ct.TransformFinalBlock(input, 0, input.Length);
return Convert.ToBase64String(buffer);
}
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;
}
This is my code against above :
public String encryptDES(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest(getNativeKey3().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(digestOfPassword, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
return Base64.encodeToString(cipherText, Base64.DEFAULT)
.replace("\n", "")
.replace("\r", "");
}
Problem :
First Code gives below result :
Encrypted Text for 121212 is VvRQkSUj5SQ69mGXsL+h6w==
But Second Code returns this :
Encrypted Text for 121212 is 2STVJSd1mnw=
Observations :
When I increase the plainttext to 10 digits I am getting 24 digit cipher text
Can any one help me in this:
Thanks in Advance
You've been fooled by the badly named Unicode class, which actually specifies UTF-16LE rather than UTF-8.
You can use StandardCharsets.UTF_16LE for specifying the encoding rather than the string; this saves you from one exception to handle.
If there are still issues with the length (test!) then you may have to deal with the Byte Order Mark or BOM - but I don't think so.
C# Code
namespace MWS.DAL
{
public class StringHelpers
{
#region Constants
private const char QUERY_STRING_DELIMITER = '&';
#endregion Constants
#region Members
private static RijndaelManaged _cryptoProvider;
//128 bit encyption: DO NOT CHANGE
private static readonly byte[] Key = { some byte value };
private static readonly byte[] IV = { some byte value };
#endregion Members
#region Constructor
static StringHelpers()
{
_cryptoProvider = new RijndaelManaged();
_cryptoProvider.Mode = CipherMode.CBC;
_cryptoProvider.Padding = PaddingMode.PKCS7;
}
#endregion Constructor
#region Methods
/// <summary>
/// Encrypts a given string.
/// </summary>
/// <param name="unencryptedString">Unencrypted string</param>
/// <returns>Returns an encrypted string</returns>
public static string Encrypt(string unencryptedString)
{
byte[] bytIn = ASCIIEncoding.ASCII.GetBytes(unencryptedString);
// Create a MemoryStream
MemoryStream ms = new MemoryStream();
// Create Crypto Stream that encrypts a stream
CryptoStream cs = new CryptoStream(ms,
_cryptoProvider.CreateEncryptor(Key, IV),
CryptoStreamMode.Write);
// Write content into MemoryStream
cs.Write(bytIn, 0, bytIn.Length);
cs.FlushFinalBlock();
byte[] bytOut = ms.ToArray();
return Convert.ToBase64String(bytOut);
}
/// <summary>
/// Decrypts a given string.
/// </summary>
/// <param name="encryptedString">Encrypted string</param>
/// <returns>Returns a decrypted string</returns>
public static string Decrypt(string encryptedString)
{
if (encryptedString.Trim().Length != 0)
{
// Convert from Base64 to binary
byte[] bytIn = Convert.FromBase64String(encryptedString);
// Create a MemoryStream
MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
// Create a CryptoStream that decrypts the data
CryptoStream cs = new CryptoStream(ms,
_cryptoProvider.CreateDecryptor(Key, IV),
CryptoStreamMode.Read);
// Read the Crypto Stream
StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
}
else
{
return "";
}
}
public static NameValueCollection DecryptQueryString(string queryString)
{
if (queryString.Length != 0)
{
//Decode the string
string decodedQueryString = HttpUtility.UrlDecode(queryString);
//Decrypt the string
string decryptedQueryString = StringHelpers.Decrypt(decodedQueryString);
//Now split the string based on each parameter
string[] actionQueryString = decryptedQueryString.Split(new char[] { QUERY_STRING_DELIMITER });
NameValueCollection newQueryString = new NameValueCollection();
//loop around for each name value pair.
for (int index = 0; index < actionQueryString.Length; index++)
{
string[] queryStringItem = actionQueryString[index].Split(new char[] { '=' });
newQueryString.Add(queryStringItem[0], queryStringItem[1]);
}
return newQueryString;
}
else
{
//No query string was passed in.
return null;
}
}
public static string EncryptQueryString(NameValueCollection queryString)
{
//create a string for each value in the query string passed in.
string tempQueryString = "";
for (int index = 0; index < queryString.Count; index++)
{
tempQueryString += queryString.GetKey(index) + "=" + queryString[index];
if (index != queryString.Count - 1)
{
tempQueryString += QUERY_STRING_DELIMITER;
}
}
return EncryptQueryString(tempQueryString);
}
/// <summary>
/// You must pass in a string that uses the QueryStringHelper.DELIMITER as the delimiter.
/// This will also append the "?" to the beginning of the query string.
/// </summary>
/// <param name="queryString"></param>
/// <returns></returns>
public static string EncryptQueryString(string queryString)
{
return "?" + HttpUtility.UrlEncode(StringHelpers.Encrypt(queryString));
}
#endregion Methods
}
}
Java Code
public String decrypt(String text) throws Exception{
// byte[] keyBytess={some byte values};
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes= new byte[16];
byte[] b= { some byte values };
byte[] iv = { some byte values };
int len= b.length;
if (len > keyBytes.length) len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);
BASE64Decoder decoder = new BASE64Decoder();
byte [] results = cipher.doFinal(decoder.decodeBuffer(text));
return new String(results,"UTF-8");
}
public String encrypt(String text)
throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes= new byte[16];
byte[] b= { some byte values };
byte[] iv = { some byte values };
int len= b.length;
if (len > keyBytes.length) len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivSpec);
byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(results);
}
In Case of C#
value= just4fun
and
ecncrypted value= j/Rph4d/Op6sugBxZ/kJbA==
In Case of Java
value= just4fun
and
encrypted value= 8BfD/Jr0Hk35qn8DXwFHmA==
and when I am trying to decrypt C# encrypted value in java it giving javax.crypto.BadPaddingException: Given final block not properly padded
I have some restriction, I can't update C# code it is in use
When you encrypt/decrypt you are using using UTF-8 Encoding in Java
byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
and ASCII in C#
byte[] bytIn = ASCIIEncoding.ASCII.GetBytes(unencryptedString);
You should get the same results when using UFT-8 encoding, like for C#:
byte[] bytIn = UTF8Encoding.UTF8.GetBytes(unencryptedString);
or for Java:
byte[] bytIn = text.getBytes("US_ASCII");
As Fildor mentioned the different PaddingModes see the comment below by James K Polk
I added a quote from msdn.microsoft.com forums for additional information
PKCS7 padding in .Net vs PKCS5 padding in Java
The difference between the PKCS#5 and PKCS#7 padding mechanisms is the block size; PKCS#5 padding is defined for 8-byte block sizes, PKCS#7 padding would work for any block size from 1 to 255 bytes. So fundamentally PKCS#5 padding is a subset of PKCS#7 padding for 8 byte block sizes.
! so, data encrypted with PKCS#5 is able to decrypt with PKCS#7, but data encrypted with PKCS#7 may not be able to decrypt with PKCS#5.
Also found a possible duplicate for your problem here.
On server (PHP code), we have 2 methods to encrypt/decrypt facebook id like this:
private function encryptFacebookId($text)
{
$method = "AES-256-CBC";
$iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted = openssl_encrypt($text, $method, $this->_cryptKey, 0, $iv);
return base64_encode($iv . $encrypted);
}
public function decryptFacebookId($text)
{
$text = base64_decode($text);
$method = "AES-256-CBC";
$iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC);
$iv = substr($text, 0, $iv_size);
$decrypted = openssl_decrypt(substr($text, $iv_size), $method, $this->_cryptKey, 0, $iv);
return $decrypted;
}
with _cryptKey="1231238912389123asdasdklasdkjasd";
It's OK with the same value of input and output at server. But When I'm connecting to server as client (Android/Java) by HTTP request (REST).
I try to convert method of PHP code to Java code at method "encryptFacebookId($text)" and send encryption text to server but the result of method decryptFacebookId($text) at server is not same value with the client.
This is my code at client
String facebookId = "123456789";
String keyCrypt = "1231238912389123asdasdklasdkjasd";
try {
SecretKeySpec skeySpec = new SecretKeySpec(keyCrypt.getBytes(),
"AES");
Cipher enCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] ivData = new byte[enCipher.getBlockSize()];
IvParameterSpec iv = new IvParameterSpec(ivData);
enCipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encryptedBytes = enCipher.doFinal(facebookId.getBytes());
String ivEncrypted = new String(ivData)
+ new String(encryptedBytes);
String strEncode = Base64
.encodeBase64String(ivEncrypted.getBytes());
System.out.println(strEncode);
} catch (Exception e) {
System.out.println(e.getMessage());
}
Please help me to find the right way.
1) If you want to concat binary byte[] don't transform it to String use for example:
public static byte[] concat(byte[]... args)
{
int fulllength = 0;
for (byte[] arrItem : args) {
fulllength += arrItem.length;
}
byte[] outArray = new byte[fulllength];
int start = 0;
for (byte[] arrItem : args) {
System.arraycopy(arrItem, 0, outArray, start, arrItem.length);
start += arrItem.length;
}
return outArray;
}
byte[] ivEncrypted = concat(ivData, encryptedBytes);
2) You have to be sure that the Base64 encoders are compatible.
I have a PHP servor which decrypt data in 3DES with the CFB Mode
I encrypt in PHP :
$montant = "500";
$message_crypte = mcrypt_encrypt(MCRYPT_3DES, "N4y1FRDRJ7wn7eJNnWaahCIS", $montant, ,CRYPT_MODE_CFB, "NCNPJDcR");
$montant = base64_encode($message_crypte);
This script in PHP is OK with other system.
And I want to encrypt in Java :
public class CryptData {
private KeySpec keySpec;
private SecretKey key;
private IvParameterSpec iv;
public CryptData(String keyString, String ivString) {
try {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest(Base64
.decodeBase64(keyString.getBytes("ISO-8859-1")));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
//keySpec = new DESedeKeySpec(keyBytes);
keySpec = new DESedeKeySpec(keyString.getBytes());
key = SecretKeyFactory.getInstance("DESede")
.generateSecret(keySpec);
iv = new IvParameterSpec(ivString.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
public String encrypt(String value) {
try {
Cipher ecipher = Cipher.getInstance("DESede/CFB/NoPadding");
//"SunJCE");
ecipher.init(Cipher.ENCRYPT_MODE, key, iv);
if (value == null)
return null;
// Encode the string into bytes using utf-8
byte[] valeur = value.getBytes("ISO-8859-1");
//byte[] utf8 = value.getBytes();
// Encrypt
byte[] enc = ecipher.doFinal(valeur);
// Encode bytes to base64 to get a string
return new String(Base64.encodeBase64(enc), "ISO-8859-1");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
I have not the same result in PHP and in Java
How modify Java treatment to obtain the same result as PHP?
The answer is:
Cipher ecipher = Cipher.getInstance("DESede/CFB8/NoPadding");
I need to use "CFB8"