I received an encrypted string from Java, and I can see the Java encrypted source code.
I wrote the decryption code in C#. But always report an error at "FlushFinalBlock". Error message: "System.Security.Cryptography.CryptographicException. Additional information: Incorrect data."
Can any body point out where the problem is in my C# code?
this is java code:
private static byte[] coderByDES(byte[] plainText, String key, int mode)
throws InvalidKeyException, InvalidKeySpecException,
NoSuchAlgorithmException, NoSuchPaddingException,
BadPaddingException, IllegalBlockSizeException,
UnsupportedEncodingException {
SecureRandom sr = new SecureRandom();
byte[] resultKey = makeKey(key);
DESKeySpec desSpec = new DESKeySpec(resultKey);
SecretKey secretKey = SecretKeyFactory.getInstance("DES").generateSecret(desSpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(mode, secretKey, sr);
return cipher.doFinal(plainText);
}
private static byte[] makeKey(String key)
throws UnsupportedEncodingException {
byte[] keyByte = new byte[8];
byte[] keyResult = key.getBytes("UTF-8");
for (int i = 0; i < keyResult.length && i < keyByte.length; i++) {
keyByte[i] = keyResult[i];
}
return keyByte;
}
private static String byteArr2HexStr(byte[] arrB) {
int iLen = arrB.length;
StringBuilder sb = new StringBuilder(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
while (intTmp < 0) {
intTmp = intTmp + 256;
}
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
this is C# code:
public static string DecryptForDES(string input, string key)
{
byte[] inputByteArray = HexStr2ByteArr(input);
byte[] buffArray = null;
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = Encoding.UTF8.GetBytes(key);
des.IV = Encoding.UTF8.GetBytes(key);
des.Mode = System.Security.Cryptography.CipherMode.ECB;
des.Padding = PaddingMode.PKCS7;
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();//
cs.Close();
}
buffArray = ms.ToArray();
ms.Close();
}
string str = string.Empty;
if (buffArray != null)
{
str = Encoding.UTF8.GetString(buffArray);
}
return str;
}
public static byte[] HexStr2ByteArr(string strIn)
{
byte[] arrB = Encoding.UTF8.GetBytes(strIn);
int iLen = arrB.Length;
byte[] arrOut = new byte[iLen / 2];
byte[] arrTmp = new byte[2];
for (int i = 0; i < iLen; i = i + 2)
{
string strTmp = Encoding.UTF8.GetString(arrB, i, 2);
arrOut[i / 2] = (byte)Convert.ToInt32(strTmp, 16);
}
return arrOut;
}
Both, the Java encryption part and the C# decryption part work on my machine if the passwords match. Otherwise a System.Security.Cryptography.CryptographicException: 'Bad Data' is thrown. To get the password match replace in the C#-method DecryptForDES
des.Key = Encoding.UTF8.GetBytes(key);
with
des.Key = MakeKey(key);
with the C#-method:
private static byte[] MakeKey(String key)
{
byte[] keyByte = new byte[8];
byte[] keyResult = Encoding.UTF8.GetBytes(key);
for (int i = 0; i<keyResult.Length && i<keyByte.Length; i++) {
keyByte[i] = keyResult[i];
}
return keyByte;
}
corresponding to the Java-method makeKey(String key).
Moreover, remove in the C#-method DecryptForDES
des.IV = Encoding.UTF8.GetBytes(key);
since the ECB-mode doesn't use an IV.
In the following testcase
coderByDES("This is a plain text that needs to be encrypted...", "This is the key used for encryption...", Cipher.ENCRYPT_MODE);
returns the byte-array
a47b1b2c90fb3b7a0ab1f51f328ff55aae3c1eb7789c31c28346696a8b1f27c7413c14e68fe977d3235b5a6f63c07d7a95d912ff22f17ad6
and
DecryptForDES("a47b1b2c90fb3b7a0ab1f51f328ff55aae3c1eb7789c31c28346696a8b1f27c7413c14e68fe977d3235b5a6f63c07d7a95d912ff22f17ad6", "This is the key used for encryption...");
returns the correct plain text.
By the way: As Flydog57 already stated DES is insecure (https://en.wikipedia.org/wiki/Data_Encryption_Standard). And also the ECB mode is not secure (https://crypto.stackexchange.com/questions/20941/why-shouldnt-i-use-ecb-encryption).
Better choices are AES (https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) with CBC or GCM mode (https://crypto.stackexchange.com/questions/2310/what-is-the-difference-between-cbc-and-gcm-mode).
Related
I am new at flutter development, I am trying to use send ENCRYPTED data on server using a public key in flutter .
I have .cer certificate and i have RSA public key in flutter. Now in Java I'm using for Encrypt the Plain Text using RSA public key i have done this
successfully . How can i do this in flutter ?
public String encrypt(String string, final X509Certificate x509Certificate) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
Cipher a = Cipher.getInstance("RSA");
final KeyGenerator instance;
(instance = KeyGenerator.getInstance("AES")).init(256);
byte[] b = instance.generateKey().getEncoded();
System.out.println("print encoded key"+b);
printUnsignedBytes(b);
aesKey = b;
new SecretKeySpec(b, "AES");
a.init(1, x509Certificate.getPublicKey());
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final CipherOutputStream cipherOutputStream;
(cipherOutputStream = new CipherOutputStream(byteArrayOutputStream, a)).write(b);
cipherOutputStream.close();
byte[] c = byteArrayOutputStream.toByteArray();
final byte[] array = new byte[16];
new SecureRandom().nextBytes(array);
final Cipher instance2;
(instance2 = Cipher.getInstance("AES/CBC/NOPADDING")).init(1, new SecretKeySpec(b, "AES"),
new IvParameterSpec(array));
byte[] bytes = s.getBytes();
int remainder = 16 - (bytes.length % 16);
byte[] remainderFilledWithSpaces = new byte[remainder];
for (int i = 0; i < remainderFilledWithSpaces.length; i++) {
remainderFilledWithSpaces[i] = " ".getBytes()[0];
}
int totalLength = bytes.length + remainder;
ByteBuffer bb = ByteBuffer.allocate(totalLength);
bb.put(bytes);
bb.put(remainderFilledWithSpaces);
bb.position(0);
byte[] blockToEncrypt = new byte[16];
ByteBuffer encrypted = ByteBuffer.allocate(totalLength);
while (bb.hasRemaining()) {
bb.get(blockToEncrypt);
byte[] update = instance2.update(blockToEncrypt);
encrypted.put(update);
}
instance2.doFinal();
final ByteArrayOutputStream byteArrayOutputStream2 = new ByteArrayOutputStream();
final byte[] array2;
(array2 = new byte[4])[0] = 0;
array2[1] = 1;
array2[3] = (array2[2] = 0);
byteArrayOutputStream2.write(array2, 0, 4);
array2[0] = 16;
array2[1] = 0;
array2[3] = (array2[2] = 0);
byteArrayOutputStream2.write(array2, 0, 4);
byteArrayOutputStream2.write(c, 0, 256);
byteArrayOutputStream2.write(array, 0, 16);
byteArrayOutputStream2.write(encrypted.array());
return s = new String(Base64.getMimeEncoder().encode(byteArrayOutputStream2.toByteArray()));
}
Now , I want this same solution in Dart .Please help,thanks a lot.
I'm facing an issue trying to Decrypt a string which has been encrypted in Java with the following properties (Java code)
public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
return new Builder()
.setIv(iv)
.setKey(key)
.setSalt(salt)
.setKeyLength(128)
.setKeyAlgorithm("AES")
.setCharsetName("UTF8")
.setIterationCount(1)
.setDigestAlgorithm("SHA1")
.setBase64Mode(Base64.DEFAULT)
.setAlgorithm("AES/CBC/PKCS5Padding")
.setSecureRandomAlgorithm("SHA1PRNG")
.setSecretKeyType("PBKDF2WithHmacSHA1");
}
This is my code so far (C#)
public string DecryptText(string encryptedString)
{
using (myRijndael = new RijndaelManaged())
{
myRijndael.Key = Convert.FromBase64String(encryptionKey);
myRijndael.IV = new byte[16];
myRijndael.Mode = CipherMode.CBC;
myRijndael.Padding = PaddingMode.PKCS7;
Byte[] ourEnc = Convert.FromBase64String(encryptedString);
string ourDec = DecryptStringFromBytes(ourEnc, myRijndael.Key, myRijndael.IV);
return ourDec;
}
}
protected string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
But when I try to decrypt I get the following exception "System.Security.Cryptography.CryptographicException: 'Specified key is not a valid size for this algorithm.'
".
The origin of the Java code resides here
https://github.com/simbiose/Encryption/blob/master/Encryption/main/se/simbio/encryption/Encryption.java
This is the Java code when encrypting
public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
if (data == null) return null;
SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());
}
private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());
}
private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
messageDigest.update(key.getBytes(mBuilder.getCharsetName()));
return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();
}
I've been struggling with this for two day since I haven't really worked a lot with encryption, so any help would be greatly appreciated.
Thanks!
Update:
Whole class
public sealed class MyCryptoClass
{
protected RijndaelManaged myRijndael;
private static string encryptionKey = "random";
// Singleton pattern used here with ensured thread safety
protected static readonly MyCryptoClass _instance = new MyCryptoClass();
public static MyCryptoClass Instance
{
get { return _instance; }
}
public MyCryptoClass()
{
}
public string DecryptText(string encryptedString)
{
using (myRijndael = new RijndaelManaged())
{
myRijndael.Key = Convert.FromBase64String(encryptionKey);
myRijndael.IV = new byte[16];
myRijndael.Mode = CipherMode.CBC;
myRijndael.Padding = PaddingMode.PKCS7;
Byte[] ourEnc = Convert.FromBase64String(encryptedString);
string ourDec = DecryptStringFromBytes(ourEnc, myRijndael.Key, myRijndael.IV);
return ourDec;
}
}
public string EncryptText(string plainText)
{
using (myRijndael = new RijndaelManaged())
{
myRijndael.Key = HexStringToByte(encryptionKey);
myRijndael.IV = HexStringToByte(initialisationVector);
myRijndael.Mode = CipherMode.CBC;
myRijndael.Padding = PaddingMode.PKCS7;
byte[] encrypted = EncryptStringToBytes(plainText, myRijndael.Key, myRijndael.IV);
string encString = Convert.ToBase64String(encrypted);
return encString;
}
}
protected byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
protected string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
public static void GenerateKeyAndIV()
{
// This code is only here for an example
RijndaelManaged myRijndaelManaged = new RijndaelManaged();
myRijndaelManaged.Mode = CipherMode.CBC;
myRijndaelManaged.Padding = PaddingMode.PKCS7;
myRijndaelManaged.GenerateIV();
myRijndaelManaged.GenerateKey();
string newKey = ByteArrayToHexString(myRijndaelManaged.Key);
string newinitVector = ByteArrayToHexString(myRijndaelManaged.IV);
}
protected static byte[] HexStringToByte(string hexString)
{
try
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}
catch
{
throw;
}
}
public static string ByteArrayToHexString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
}
Since your MyCryptoClass.encryptionKey corresponds to your Encryption.Builder.mKey you have to generate the secret key on the C#-side i.e. you have to implement on the C# side a counterpart for each Java-method involved in this process. These Java-methods are getSecretKey(char[] key), hashTheKey(String key) and also third.part.android.util.Base64.encodeToString(byte[] input, int flags).
Possible C#-Counterpart of the Java-method getSecretKey(char[] key):
private static byte[] GetSecretKey()
{
string hashedKey = GetHashedKey();
byte[] saltBytes = Encoding.UTF8.GetBytes(salt); // builder.mCharsetName = "UTF8";
int iterations = 1; // builder.mIterationCount = 1
byte[] secretKey = null;
using (Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(hashedKey, saltBytes, iterations)) // builder.mSecretKeyType = "PBKDF2WithHmacSHA1";
{
secretKey = rfc2898.GetBytes(16); // builder.mKeyLength = 128;
//Console.WriteLine("Key: " + ByteArrayToHexString(secretKey));
}
return secretKey;
}
This method derives a secret key using PBKDF2WithHmacSHA1 with a key, salt, iterationcount and key length as input. The key (more precisely password) used here is a base64-encoded SHA1-hash from MyCryptoClass.encryptionKey provided by GetHashedKey() (see below).
Possible C#-Counterpart of the Java-method hashTheKey(String key):
private static string GetHashedKey()
{
string hashBase64 = String.Empty;
using (SHA1Managed sha1 = new SHA1Managed()) // builder.mDigestAlgorithm = "SHA1";
{
byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(encryptionKey)); // builder.mCharsetName = "UTF8";
hashBase64 = Base64ThirdPartAndroid(hash, true);
//Console.WriteLine("Hash (base64): " + hashBase64);
}
return hashBase64;
}
This method derives a SHA1-hash from MyCryptoClass.encryptionKey and base64-encodes that hash. For the base64-encoding the method Base64ThirdPartAndroid(byte[] arr, bool withoutPadding) (see below) is used.
Possible C#-Counterpart of the Java-method third.part.android.util.Base64.encodeToString(byte[] input, int flags) ( https://github.com/simbiose/Encryption/blob/master/Encryption/main/third/part/android/util/Base64.java):
private static string Base64ThirdPartAndroid(byte[] arr, bool withoutPadding)
{
string base64String = System.Convert.ToBase64String(arr);
if (withoutPadding) base64String = base64String.TrimEnd('='); // Remove trailing "="-characters
base64String += "\n"; // Append LF (10)
//Console.WriteLine("Array as base64 encoded string: " + base64String);
return base64String;
}
In the Java code third.part.android.util.Base64.encodeToString(byte[] input, int flags) is used with flags = Base64.NO_PADDING which removes the "="-character at the end of the base64-encoded string. Additionally a line feed (LF, \n, ASCII value: 10) is appended. If a Base64-Encoding is used which doesn't remove the "="-characters or without a terminating line feed, the decryption will fail since the hash is the base of the later generated secret key which have to match on the encryption and on the decryption side. To the best of my knowledge there is no Base64-encoding on the C# side with the necessary characteristics. However, if there is such an encoding you can use it of course.
Add all three C#-counterparts to your MyCryptoClass class.
Additionally (to the static field encryptionKey) add the static fields initialisationVector, salt and secretKey to your MyCryptoClass-class and assign the following values for testing purposes:
private static string encryptionKey = "A7zb534OPq59gU7q";
private static string salt = "JV5k9GoH";
private static byte[] initialisationVector = Encoding.UTF8.GetBytes("l4iG63jN9Dcg6537");
private static byte[] secretKey = GetSecretKey();
The type of the parameters corresponds to the type in the Java code (encryptionKey and salt are strings, the initialisationVector is a byte-array). The secret key generated by GetSecretKey() is stored in the byte-array secretKey.
In your C# DecryptText- and EncryptText-method set myRijndael.Key and myRijndael.IV to
myRijndael.Key = secretKey;
myRijndael.IV = initialisationVector;
Test the modifications as follows:
With your Java encrypt-method encrypt the following plain text:
Test: The quick brown fox jumps over the lazy dog...
using the key/salt/iv above with
mBuilder = Builder.getDefaultBuilder("A7zb534OPq59gU7q","JV5k9GoH","l4iG63jN9Dcg6537".getBytes("UTF-8"));
The encrypted text is:
mL4ajZtdRgD8CtGSfJGkT24Ebw4SrGUGKQI6bvBw1ziCO/J7SeLiyIw41zumTHMMD9GOYK+kR79CVcpoaHT9TQ==
Decrypting this using the C# DecryptText-method gives again the plain text. Below are two test cases:
static void Main(string[] args)
{
// Test 1: Encrypted text from C#
MyCryptoClass mcc = MyCryptoClass.Instance;
string encryptedText = mcc.EncryptText("This is a plain text which needs to be encrypted...");
Console.WriteLine("Encrypted text (base64): " + encryptedText);
string decryptedText = mcc.DecryptText(encryptedText);
Console.WriteLine("Decrypted text: " + decryptedText);
// Test 2: Encrypted text from Java
string javaEncryptedText = "mL4ajZtdRgD8CtGSfJGkT24Ebw4SrGUGKQI6bvBw1ziCO/J7SeLiyIw41zumTHMMD9GOYK+kR79CVcpoaHT9TQ==";
Console.WriteLine("Encrypted text from Java (base64): " + javaEncryptedText);
string javaDecryptedText = mcc.DecryptText(javaEncryptedText);
Console.WriteLine("Decrypted text from Java: " + javaDecryptedText);
}
Following is Full C# class which i were able to work as it is like java class
At the moment i have only checked encryption part
public sealed class MyCryptoClass
{
protected AesManaged myRijndael;
private static string encryptionKey = "MyKey";
private static string salt = "Mysalt";
private static byte[] initialisationVector = new byte[16];
//private static byte[] initialisationVector = Encoding.UTF8.GetBytes("l4iG63jN9Dcg6537");
private static byte[] secretKey = GetSecretKey();
// Singleton pattern used here with ensured thread safety
protected static readonly MyCryptoClass _instance = new MyCryptoClass();
public static MyCryptoClass Instance
{
get { return _instance; }
}
public MyCryptoClass()
{
}
public string DecryptText(string encryptedString)
{
using (myRijndael = new AesManaged())
{
myRijndael.Key = Convert.FromBase64String(encryptionKey);
myRijndael.IV = new byte[16];
myRijndael.Mode = CipherMode.CBC;
myRijndael.Padding = PaddingMode.PKCS7;
Byte[] ourEnc = Convert.FromBase64String(encryptedString);
string ourDec = DecryptStringFromBytes(ourEnc, myRijndael.Key, myRijndael.IV);
return ourDec;
}
}
public string EncryptText(string plainText)
{
using (myRijndael = new AesManaged())
{
myRijndael.Key = secretKey;
myRijndael.IV = initialisationVector;
myRijndael.Mode = CipherMode.CBC;
myRijndael.Padding = PaddingMode.PKCS7;
byte[] encrypted = EncryptStringToBytes(plainText, myRijndael.Key, myRijndael.IV);
string encString = Convert.ToBase64String(encrypted);
return encString;
}
}
protected byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
protected string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
public static void GenerateKeyAndIV()
{
// This code is only here for an example
AesManaged myRijndaelManaged = new AesManaged();
myRijndaelManaged.Mode = CipherMode.CBC;
myRijndaelManaged.Padding = PaddingMode.PKCS7;
myRijndaelManaged.GenerateIV();
myRijndaelManaged.GenerateKey();
string newKey = ByteArrayToHexString(myRijndaelManaged.Key);
string newinitVector = ByteArrayToHexString(myRijndaelManaged.IV);
}
protected static byte[] HexStringToByte(string hexString)
{
try
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}
catch
{
throw;
}
}
public static string ByteArrayToHexString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
private static byte[] GetSecretKey()
{
string hashedKey = GetHashedKey();
byte[] saltBytes = Encoding.UTF8.GetBytes(salt); // builder.mCharsetName = "UTF8";
int iterations = 1; // builder.mIterationCount = 1
byte[] secretKey = null;
using (Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(hashedKey, saltBytes, iterations)) // builder.mSecretKeyType = "PBKDF2WithHmacSHA1";
{
secretKey = rfc2898.GetBytes(16); // builder.mKeyLength = 128;
//Console.WriteLine("Key: " + ByteArrayToHexString(secretKey));
}
return secretKey;
}
private static string GetHashedKey()
{
string hashBase64 = String.Empty;
using (SHA1Managed sha1 = new SHA1Managed()) // builder.mDigestAlgorithm = "SHA1";
{
byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(encryptionKey)); // builder.mCharsetName = "UTF8";
hashBase64 = Base64ThirdPartAndroid(hash, true);
//hashBase64 = Base64ThirdPartAndroid(hash, true);
//Console.WriteLine("Hash (base64): " + hashBase64);
}
return hashBase64;
}
private static string Base64ThirdPartAndroid(byte[] arr, bool withoutPadding)
{
string base64String = System.Convert.ToBase64String(arr);
if (withoutPadding) base64String = base64String.TrimEnd('='); // Remove trailing "="-characters
base64String += "\n"; // Append LF (10)
//Console.WriteLine("Array as base64 encoded string: " + base64String);
return base64String;
}
}
this method is 100% working for encryption
public static string AESDecrypt(string text, string secretKey)
{
try
{
SHA1 sha = new SHA1CryptoServiceProvider();
RijndaelManaged aes = new RijndaelManaged();
byte[] finalKey = new byte[16]; // Used to generate finalKey
byte[] byteDataToDecrypt = Convert.FromBase64String(text); // Converting Base64 data to Byte Array
byte[] byteSecretKey = Encoding.UTF8.GetBytes(secretKey); // Converting secret key in byte array
byte[] hashSecretKey = sha.ComputeHash(byteSecretKey); // geneating hash in byte array of secret key
Array.Copy(hashSecretKey, finalKey, 16); // copying fist 16 bytes from hashed secret key to finaly key which to use in algo
aes.KeySize = 128;
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.ECB;
aes.Key = finalKey;
using (ICryptoTransform decrypt = aes.CreateDecryptor(aes.Key, null)) //Passing IV as NULL because IV is not present in the Java Code
{
byte[] dest = decrypt.TransformFinalBlock(byteDataToDecrypt, 0, byteDataToDecrypt.Length);
decrypt.Dispose();
return Encoding.UTF8.GetString(dest);
}
}
catch (Exception ex)
{
throw ex;
}
}
I am developing a REST API in which the data to be passed to the server need to be encrypted with 'AES/CBC/PKCS5Padding'. The REST API client side is using Java to encrypt and decrypt the data, while on my side I am using PHP.
The secret key used here is hash with sha1. I have the same secret key value with the client side and also the IV value is the same, but when I try to encrypt and compare it to the client, it's different.
JAVA Code:
import java.util.Arrays;
import java.security.*;
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.lang.Object;
class Main {
public static String stringToHex(String base)
{
StringBuffer buffer = new StringBuffer();
int intValue;
for(int x = 0; x < base.length(); x++)
{
int cursor = 0;
intValue = base.charAt(x);
String binaryChar = new String(Integer.toBinaryString(base.charAt(x)));
for(int i = 0; i < binaryChar.length(); i++)
{
if(binaryChar.charAt(i) == '1')
{
cursor += 1;
}
}
if((cursor % 2) > 0)
{
intValue += 128;
}
buffer.append(Integer.toHexString(intValue) + " ");
}
return buffer.toString();
}
public static String bytesToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for(byte b: a)
sb.append(String.format("%02x", b));
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException,
InvalidAlgorithmParameterException,
NoSuchProviderException,
NoSuchPaddingException,
InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException
{
MessageDigest sha = MessageDigest.getInstance("SHA-1");
String secretKey = "mysecretkey102018";
String message = "00155001C"
byte[] key = sha.digest(secretKey.getBytes("UTF-8"));
byte[] value = message.getBytes();
key = Arrays.copyOf(key, 16);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec iv = new IvParameterSpec("AAAAAAAAAAAAAAAA".getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
System.out.println(bytesToHex(cipher.doFinal(value)));
}
PHP Code:
class IDebit
{
private $iv = "AAAAAAAAAAAAAAAA";
private $secret_key = "mysecretkey102018";
private $message = "00155001C";
public function generateEncrytedKeyId()
{
$hashPassword = substr(hash("SHA1", $secret_key), 0, 32);
$blocksize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$str = $this->pkcs5_pad($message, $blocksize);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $hashPassword, $str, MCRYPT_MODE_CBC, self::IV);
return bin2hex($encrypted);
}
protected function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
}
The encryption result on Java is c1e7af770d9d0af59cc75d1c76aa78f6, while on PHP is d67a15a027be7e7ab68ea6ab88ea4f2f
I'm wondering what is wrong with my code. I have googled and check on this forum about the question dozens of times but I am unable to get the same result. I have rechecked my code with the answers posted by people on this forum and it's identical.
Recently i've post a question about this topic but the thing turns a little weird when i tried to decrypt an AES String that was encoded on UTF8
In the following lines i read the String AES encrypted wich returns the following String: RnLObq9hdUDGp9S2pxC1qjQXekuf9g6i/5bQfKilYn4=
public static final String AesKey256 ="ZzRtNDNuY3J5cHRrM3kuLi4=";
//This reads the String and stores on res.getContents()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult res= IntentIntegrator.parseActivityResult(requestCode, resultCode,data);
if(res!=null){
if (res.getContents() == null) {
Toast.makeText(this,"Captura cancelada",Toast.LENGTH_SHORT).show();
}else{
try {
String cadena= decrypt(res.getContents());
out.setText(cadena);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//provide the res.getContents() to decrypt method, wich its the String i've recently read
private String decrypt(String cadena)throws Exception{
SecretKeySpec keySpec= generateKey(AesKey256); //HERE
Cipher c= Cipher.getInstance(AES_MODE);
c.init(Cipher.DECRYPT_MODE,keySpec);
byte[] decodedValue= Base64.decode(cadena, Base64.DEFAULT);
byte[] decValue= c.doFinal(decodedValue);/* c.doFinal(decodedValue);*/
String decryptedValue= new String((decValue), "UTF-8");
return decryptedValue;
}
private SecretKeySpec generateKey(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
final MessageDigest digest= MessageDigest.getInstance("SHA-256");
byte[] bytes= password.getBytes("UTF-8");
digest.update(bytes,0,bytes.length);
byte[] key= digest.digest();
SecretKeySpec secretKeySpec= new SecretKeySpec(key, "AES");
return secretKeySpec;
}
I am only using the decryption method but it still returning this characters:
i've spent hours looking for a solution, but nothing works for now... hope someone can give me a hand!
Best Regards!
EDIT
THIS IS HOW IT WAS ENCRYPTED IN C#
private const string AesIV256 = "IVFBWjJXU1gjRURDNFJGVg==";
private const string AesKey256 = "ZzRtNDNuY3J5cHRrM3kuLi4=";
public static string Encrypt(string text)
{
var sToEncrypt = text;
var rj = new RijndaelManaged()
{
Padding = PaddingMode.Zeros,
Mode = CipherMode.ECB,
KeySize = 256,
BlockSize = 256,
};
var key = Convert.FromBase64String(AesKey256);
var IV = Convert.FromBase64String(AesIV256);
var encryptor = rj.CreateEncryptor(key, IV);
var msEncrypt = new MemoryStream();
var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
var toEncrypt = Encoding.UTF8.GetBytes(sToEncrypt);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
var encrypted = msEncrypt.ToArray();
return (Convert.ToBase64String(encrypted));
}
Made it!
After a long time of searching thanks to all you guys who answered this post i used the bouncy castle library and i've decrypt the desired String by doing the following:
public static String decrypt(String valueToDecrypt) throws Exception {
AESCrypt enc = new AESCrypt();
return new String(enc.decryptInternal(valueToDecrypt)).trim();
}
private byte[] decryptInternal(String code) throws Exception {
if (code == null || code.length() == 0) {
throw new Exception("Empty string");
}
byte[] decrypted = null;
try {
byte[] key= SecretKey.getBytes("UTF-8");
PaddedBufferedBlockCipher c = new PaddedBufferedBlockCipher(new RijndaelEngine(256), new ZeroBytePadding());
CipherParameters params= new KeyParameter(key);`
// false because its going to decrypt
c.init(false,params);
decrypted= GetData(c,(Base64.decode(code,Base64.DEFAULT));
} catch (Exception e) {
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
private static byte[] GetData(PaddedBufferedBlockCipher cipher, byte[] data) throws InvalidCipherTextException
{
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] cipherArray = new byte[actualLength];
for (int x = 0; x < actualLength; x++) {
cipherArray[x] = outBuf[x];
}
return cipherArray;
}
I need implement login to .NET Soap Web Service. This Web Service has method
AuthenticateUser(username, password)
and password should be encrypted with RSA public key. Below what I am trying to do:
public static final String PUBLIC = "q/9CujExqL6rsMMO22WWIotoXDCw5KEmGQJqL9UJEfoErwZ9ZCm3OwMTSlAMSfoXEMA04Y1rhfYC3MtU/7dYEoREfsvOPGDBWanTKyMzv2otCfiURyQoghEdkhv3ipQQaaErT7lfBKobJsdqJlvxo4PCOUas2Z6YpoMYgthzTiM=";
public static final String EXPONENT = "AQAB";
public static PublicKey getPublicKey() throws Exception{
byte[] modulusBytes = Base64.decode(PUBLIC, 0);
byte[] exponentBytes = Base64.decode(EXPONENT, 0);
BigInteger modulus = new BigInteger(1, (modulusBytes) );
BigInteger exponent = new BigInteger(1, (exponentBytes));
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
public static byte[] encrypt(Key publicKey, String s) throws Exception{
byte[] byteData = s.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher.doFinal(byteData);
return encryptedData;
}
public static String arrayAsString (byte [] array){
String p = "";
for (int i = 0; i < array.length; i++) {
p += unsignedToBytes(array[i]);
if (i < array.length - 1)
p+= ",";
}
return p;
}
public static int unsignedToBytes(byte b) {
return b & 0xFF;
}
public static void main(String[] args){
PublicKey publicKey = getPublicKey();
byte [] encrypted = encode(publicKey, "passwordHere");
String pass = arrayAsString(encrypted);
webservice.AuthenticateUser("testAdmin", pass);
}
I also have .NET code from Web Service side
private static string publicKey = "<RSAKeyValue><Modulus>q/9CujExqL6rsMMO22WWIotoXDCw5KEmGQJqL9UJEfoErwZ9ZCm3OwMTSlAMSfoXEMA04Y1rhfYC3MtU/7dYEoREfsvOPGDBWanTKyMzv2otCfiURyQoghEdkhv3ipQQaaErT7lfBKobJsdqJlvxo4PCOUas2Z6YpoMYgthzTiM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
private static UnicodeEncoding _encoder = new UnicodeEncoding();
public static string Encrypt(string data)
{
var rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publicKey);
var dataToEncrypt = _encoder.GetBytes(data);
var encryptedByteArray = rsa.Encrypt(dataToEncrypt, false).ToArray();
var length = encryptedByteArray.Count();
var item = 0;
var sb = new StringBuilder();
foreach (var x in encryptedByteArray)
{
item++;
sb.Append(x);
if (item < length)
sb.Append(",");
}
return sb.ToString();
}
public static string Decrypt(string data)
{
var rsa = new RSACryptoServiceProvider();
var dataArray = data.Split(new char[] { ',' });
byte[] dataByte = new byte[dataArray.Length];
for (int i = 0; i < dataArray.Length; i++)
{
dataByte[i] = Convert.ToByte(dataArray[i]);
}
rsa.FromXmlString(privateKey);
var decryptedByte = rsa.Decrypt(dataByte, false);
return _encoder.GetString(decryptedByte);
}
Is somebody have any idea what I am doing wrong? Why Web Service always returns me AuthenticateUserResponse{AuthenticateUserResult=false; }
I think the problem here is may be to do with text encoding, rather than the encryption/decryption process itself. On the Java side, you're encrypting the UTF-8 encoded password, whereas on the .NET side, it's using UnicodeEncoding which is UTF-16. Try using UTF-16 on the Java side before encryption instead.