AES Java Encryption - c#

I am developing an application in java for a mobile platform. The program uses data from a Windows C# application which encrypts passwords in an online database which the mobile app will use.
The mobile app needs to connect to the database and retrieve the encrypted string from the database and decrypt it.
I have the decryption working fine using the following code
public String decrypt(String encryptedPassword)
{
String plainPassword = "";
try
{
SecretKeySpec key = new SecretKeySpec("hcxilkqbbhczfeultgbskdmaunivmfuo".getBytes("US-ASCII"), "AES");
IvParameterSpec iv = new IvParameterSpec("ryojvlzmdalyglrj".getBytes("US_ASCII"));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] encoded = cipher.doFinal(Base64.decodeBase64(encryptedPassword.getBytes()));
plainPassword = new String(encoded);
}
catch (Exception ex)
{
Log.d("Decryption Error", ex.toString());
}
return plainPassword;
}
The decryption works absolutely fine so I have used the same code from the decryption for the encryption but changed the cipher mode from decrypt to encrypt. However, when I print to the console the encrypted password it prints a load of rubbish which shows no resemblance the string that should be stored in the database.
I have used the following code in order to do the encryption
public String encrypt(String plainPasword)
{
String password = "";
try
{
SecretKeySpec key = new SecretKeySpec("hcxilkqbbhczfeultgbskdmaunivmfuo".getBytes("US-ASCII"), "AES");
IvParameterSpec iv = new IvParameterSpec("ryojvlzmdalyglrj".getBytes("US_ASCII"));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] encoded = cipher.doFinal(plainPasword.getBytes());
password = new String(encoded);
}
catch (Exception ex)
{
Log.d("Encryption Error", ex.toString());
}
return password;
}
Thanks for any help you can give me

In the decryption function you are calling
byte[] encoded = cipher.doFinal(Base64.decodeBase64(encryptedPassword.getBytes()));
so you are converting ASCII bytes to Base64 bytes, then decrypting them.
Wouldn't you do the same in the reverse, when you actually call only
byte[] encoded = cipher.doFinal(plainPasword.getBytes());
You also are creating new String() from byte[] array without specifying encoding, that uses platform's default encoding, not ASCII. That might break stuff too.
If you look at the bytes returned by cipher.doFinal() that's supposed to be gibberish, don't they have any resemblance to the expected data?

Related

GCP KMS : Encryption taking place but decryption isn't

I'm working on a project where encryption and decryption is going to be done using GCP KMS. As a part of the POC, I'm trying to create a function which encrypts and decrypts a string using KMS. While I believe encryption is happening properly, the decryption isn't happening as expected. Here is my code :
public String encryptAndDecrypt() throws IOException {
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
String plaintext = "Just an ordinary string";
CryptoKeyName keyVersionName = CryptoKeyName.of("us-con-gcp-npr-0000305-041421",
"global", "test", "test1");
// Encrypt the plaintext.
EncryptResponse response = client.encrypt(keyVersionName, ByteString.copyFromUtf8(plaintext));
String cipherText = response.getCiphertext().toStringUtf8();
System.out.printf("Ciphertext: %s%n", cipherText);
// Decrypt the ciphertext
DecryptResponse decryptResponse = client.decrypt(keyVersionName, ByteString.copyFrom(cipherText.getBytes()));
System.out.printf("Plaintext: %s%n", decryptResponse.getPlaintext().toStringUtf8());
}
return "Done";
}
I actually got this code from GCP documents. However, I keepgetting this error :
INVALID_ARGUMENT: Decryption failed: the ciphertext is invalid.
Please help
The ciphertext is a byte array and not a UTF8 encoded string. Your code is corrupting the ciphertext.
Change:
String cipherText = response.getCiphertext().toStringUtf8();
To:
byte[] cipherText = response.Ciphertext.ToByteArray();

AES decryption only producing part of the answer C#

I'm trying to learn cyber security and this is the very first thing I've done on it. I'm using this MSDN document ( https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes?redirectedfrom=MSDN&view=netcore-3.1 ) and it partly works. I assume it's encrypting it fine as when it comes to the decryption some of the original data is there but some is lost. The data that is being encrypted is a class that has been formatted into a JSON string( I don't think this is relevant as it's still a string being encrypted).
But once it's been encrypted and decrypted it turns out like this:
I've ran this code and compared the results 5+ times and it's always: the start is wrong, username is partly right, password is always right and loginkey is partly right. So the error is recurring and always in the same spot.
Information you should know, the data get's encrypted and saved to a .txt file. The programme will run again and it will try and decrypted it. The Salt and password are saved on another file and those are read and used in the decryption.
There is a similar question on stackoverflow but the answer just says to use Rijndael(so not really an answer), this code is for me to learn and want an answer that isn't 4 lines long.
Code if curious(but it's basically the same as the MSDN document):
Encryption:
static void EncryptFile()
{
string pwd1 = SteamID;//steamID is referring to account ID on Valve Steam
using (RNGCryptoServiceProvider rngCsp = new
RNGCryptoServiceProvider())
{
rngCsp.GetBytes(salt1); //salt1 is a programme variable and will get saved to a file
}
SecureData File = new SecureData(_UserName,_PassWord,_LoginKey);
string JsonFile = JsonConvert.SerializeObject(File); //puts the class into Json format
int myIterations = 1000; //not needed
try
{
Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes(pwd1, salt1,
myIterations);
Aes encAlg = Aes.Create(); // This might be the issue as AES will be different when you decrypt
encAlg.Key = k1.GetBytes(16);
MemoryStream encryptionStream = new MemoryStream();
CryptoStream encrypt = new CryptoStream(encryptionStream,
encAlg.CreateEncryptor(), CryptoStreamMode.Write);
byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(
JsonFile); //encrypt Data
encrypt.Write(utfD1, 0, utfD1.Length);
encrypt.FlushFinalBlock();
encrypt.Close();
byte[] edata1 = encryptionStream.ToArray();
k1.Reset();
System.IO.File.WriteAllBytes(SecureFile, edata1); //writes encrypted data to file
}
catch (Exception e)
{
Console.WriteLine("Error: ", e);
}
}
Decryption:
static void DecryptFile()
{
string pwd1 = SteamID;
byte[] edata1;
try
{
edata1 = System.IO.File.ReadAllBytes(SecureFile); //reads the file with encrypted data on it
Aes encAlg = Aes.Create(); //I think this is the problem as the keyvalue changes when you create a new programme
Rfc2898DeriveBytes k2 = new Rfc2898DeriveBytes(pwd1, salt1); //inputs from last time carry over
Aes decAlg = Aes.Create();
decAlg.Key = k2.GetBytes(16);
decAlg.IV = encAlg.IV;
MemoryStream decryptionStreamBacking = new MemoryStream();
CryptoStream decrypt = new CryptoStream(
decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
decrypt.Write(edata1, 0, edata1.Length);
decrypt.Flush();
decrypt.Close();
k2.Reset();
string data2 = new UTF8Encoding(false).GetString(
decryptionStreamBacking.ToArray());//decrypted data
SecureData items = JsonConvert.DeserializeObject<SecureData>(data2); //reformat it out of JSon(Crashes as format isn't accepted)
_UserName = items.S_UserName;
_PassWord = items.S_Password;
_LoginKey = items.S_LoginKey;
}
catch (Exception e)
{
Console.WriteLine("Error: ", e);
NewLogin();
}
}
Class Struct:
class SecureData
{
public string S_UserName { get; set; } //These are variables that are apart of Valve steam Login process
public string S_Password { get; set; }
public string S_LoginKey { get; set; }
public SecureData(string z, string x, string y)
{
S_UserName = z;
S_Password = x;
S_LoginKey = y;
}
}
The problem is caused by different IVs for encryption and decryption. For a successful decryption the IV from the encryption must be used.
Why are different IVs applied? When an AES instance is created, a random IV is implicitly generated. Two different AES instances therefore mean two different IVs. In the posted code, different AES instances are used for encryption and decryption. Although the reference encAlg used in the decryption has the same name as that of the encryption, the referenced instance is a different one (namely an instance newly created during decryption). This is different in the Microsoft example. There, the IV of the encryption is used in the decryption: decAlg.IV = encAlg.IV, where encAlg is the AES instance with which the encryption was performed.
The solution is to store the IV from the encryption in the file so that it can be used in the decryption. The IV is not secret and is usually placed before the ciphertext:
Necessary changes in EncryptFile:
...
byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(JsonFile);
encryptionStream.Write(encAlg.IV, 0, encAlg.IV.Length); // Write the IV
encryptionStream.Flush();
encrypt.Write(utfD1, 0, utfD1.Length);
...
Necessary changes in DecryptFile:
...
edata1 = System.IO.File.ReadAllBytes(SecureFile);
byte[] iv = new byte[16]; // Separate IV and ciphertext
byte[] ciphertext = new byte[edata1.Length - iv.Length];
Array.Copy(edata1, 0, iv, 0, iv.Length);
Array.Copy(edata1, iv.Length, ciphertext, 0, ciphertext.Length);
...
Aes encAlg = Aes.Create(); // Remove this line
...
decAlg.IV = iv; // Use the separated IV
...
decrypt.Write(ciphertext, 0, ciphertext.Length); // Use the separated ciphertext
A few remarks:
For each encryption a new, random salt should be generated and concatenated with the ciphertext analogous to the IV. During decryption, the salt can then be determined analogous to IV. Consider additionally RFC8018, sec 4.1.
The iteration count slows down the derivation of the key, which should make an attack by repeated attempts more difficult. Therefore the value should be as large as possible. Consider additionally RFC8018, sec 4.2.
Authentication data (i.e. passwords) are not encrypted, but hashed, here.

RSA Encryption and Decryption in C#.NET

I have below code to encrypt and decrypt the message in c#. when i am trying to run it is giving an exception ie "The data to be decrypted exceeds the maximum for this modulus of 256 bytes"
public static void Main(string[] args)
{
X509Certificate2 cert = new X509Certificate2(#"C:\Data\ABC-rsa-public-key-certificate.cer");
string encryptedText = EncrypIt("Hello", cert);
string decryptedText = DecrptIt(encryptedText, cert);
System.Console.WriteLine(decryptedText);
}
public static string EncrypIt(string inputString, X509Certificate2 cert)
{
RSACryptoServiceProvider publicKey = (RSACryptoServiceProvider)cert.PublicKey.Key;
byte[] plainBytes = Encoding.UTF8.GetBytes(inputString);
byte[] encryptedBytes = publicKey.Encrypt(plainBytes, false);
string encryptedText = Encoding.UTF8.GetString(encryptedBytes);
return encryptedText;
}
public static string DecrptIt(string encryptedText, X509Certificate2 cert)
{
RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)cert.PublicKey.Key;
byte[] encryptedBytes = Encoding.UTF8.GetBytes(encryptedText);
byte[] decryptedBytes = privateKey.Decrypt(encryptedBytes, false);
string decryptedText = Encoding.UTF8.GetString(decryptedBytes);
return decryptedText;
}
Several problems:
RSA by default only encrypts one block. It's not suitable for long messages. You shouldn't encrypt the message itself with RSA. Generate a random AES key and encrypt the key with RSA and the actual message with AES.
You must use a binary safe encoding such as Hex or Base64 for the ciphertext. Using UTF-8 corrupts the data since it doesn't allow arbitrary byte sequences.
UTF-8 is designed to encode text, so it's fine for your plaintext.
Use OAEP, the old 1.5 padding mode is not secure. i.e. pass true as second parameter to Encrypt/Decrypt. (Technically it's possible to use it securely, but it's tricky and I wouldn't recommend it)
As a further note, once you use AES, there are some more pitfalls: 1) Use a MAC in an encrypt-then-mac scheme, else active attacks including padding-oracles will break your code 2) Use a random IV that's different for each message
RSA should not be used to encrypt this kind of data. You should be encrypting your data with a symmetric key like AES, then encrypting the symmetric key with RSA.

Encrypt data using c# and decrypt it using openssl api, why there are lots of trashy padding at the end of decrypted data?

I using RSA(1024) to encrypt/decrypt strings. The encryption is implemented using public key and is written in C#, and the decryption is implementation by c. I encrypt the string:
86afaecb-c211-4d55-8e90-2b715d6d64b9
and write the encrypted data to a file. Then, I using openssl api to read the encrypted data from the file and decrypt it. However, I got the output as:
86afaecb-c211-4d55-8e90-2b715d6d64b9oeheBjQ8fo1AmDnor1D3BLuPyq9wJBAOV+M/WVNYzYr
PJBKoskOj+4LaNpT+SpkfK81nsnQEbHbjgao4eHNU+PmWl9
It seems that there are some trashy padding at the end of original string. Why It Occurs? And how to solve the problem?
Some code snippet is shown below:
// Encrypt
{
string plainData = “86afaecb-c211-4d55-8e90-2b715d6d64b9”;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(paraPub);
byte[] testData = Encoding.UTF8.GetBytes(plainData);
byte[] encryptedData = rsa.Encrypt(testData, true);
FileStream pFileStream = null;
string fileName = "encryptedData.dat";
pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
pFileStream.Write(encryptedData, 0, encryptedData.Length);
...
}
// Decrypt
{
char *encrypt = malloc(RSA_size(privateKey));
FILE *out = fopen("encryptedData.dat", "r");
int encrypt_len = fread(encrypt, sizeof(*encrypt), RSA_size(privateKey), out);
fclose(out);
decrypt = malloc(encrypt_len);
if(RSA_private_decrypt(encrypt_len,
(unsigned char*)encrypt,
(unsigned char*)decrypt,
privateKey, RSA_PKCS1_OAEP_PADDING) == -1) {
// error handle
}
printf("Decrypted message: %s\n", decrypt);
}
I solve the problem by initializing the decrypt using "memset(decrypt, 0, encrypt_len);" after "decrypt = malloc(encrypt_len);". Thx everyone.
The issue is that you should use the decrypted size instead of directly treating the output of the decryption as a null terminated string.
RSA_private_decrypt() returns the size of the recovered plaintext.

How to decrypt data signed by RSACryptoServiceProvider

I am starting to use encryption and decryption in my web service. I am using the RSACryptoServiceProvider and when using the Encrypt & Decrypt methods, I have no problem.
However, as soon as I try to use the SignData method with new SHA1CryptoServiceProvider() as encryption method, I am unable to recover the original data. I am only able to verify them.
Is it really not possible to retrieve the signed data? If so, what is the purpose of the whole signing process? And is there another possibility how to encrypt data by a certain algorithm?
EDIT: I am posting the code, which is just an altered example from MSDN
static void Main()
{
try
{
//Create a UnicodeEncoder to convert between byte array and string.
ASCIIEncoding ByteConverter = new ASCIIEncoding();
string dataString = "Data to Encrypt";
//Create byte arrays to hold original, encrypted, and decrypted data.
byte[] dataToEncrypt = ByteConverter.GetBytes(dataString);
byte[] encryptedData;
byte[] signedData;
byte[] decryptedData;
byte[] unsignedData;
var fileName = ConfigurationManager.AppSettings["certificate"];
var password = ConfigurationManager.AppSettings["password"];
var certificate = new X509Certificate2(fileName, password);
//Create a new instance of the RSACryptoServiceProvider class
// and automatically create a new key-pair.
RSACryptoServiceProvider RSAalg = (RSACryptoServiceProvider)certificate.PrivateKey;
//RSAPKCS1SignatureDeformatter def = (RSAPKCS1SignatureDeformatter)certificate.PrivateKey;
//Display the origianl data to the console.
Console.WriteLine("Original Data: {0}", dataString);
//Encrypt the byte array and specify no OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
encryptedData = RSAalg.Encrypt(dataToEncrypt, false);
signedData = RSAalg.SignData(dataToEncrypt, new SHA1CryptoServiceProvider());
//Display the encrypted data to the console.
Console.WriteLine("Encrypted Data: {0}", ByteConverter.GetString(encryptedData));
Console.WriteLine("Signed Data: {0}", ByteConverter.GetString(signedData));
//Pass the data to ENCRYPT and boolean flag specifying
//no OAEP padding.
decryptedData = RSAalg.Decrypt(encryptedData, false);
//In the next line I get the error of wrong data
unsignedData = RSAalg.Decrypt(signedData, false);
//Display the decrypted plaintext to the console.
Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
Console.WriteLine("Unsigned plaintext: {0}", ByteConverter.GetString(unsignedData));
}
catch (CryptographicException e)
{
//Catch this exception in case the encryption did
//not succeed.
Console.WriteLine(e.Message);
}
Console.Read();
}
SHA1 is a hash function, so you cant compute a message that has a given hash. In other words, you cant sign/unsign the message, you only can sign and verify it.

Categories