I have the following code to encrypt a value (listed below). Now I would like to write a bool isEncrypted() method. Is there a fool proof and reliable way to check if a value has been encrypted using this function. I have the decrypt routine and can control the pass phrase, but not sure if that will help.
The reason is - when the app first runs, values in a configuration file are not encrypted, in this case the app should auto encrypt these values. On 2nd run I don't want to encrypt again because obviously that would cause havoc. Lastly I don't want to have to add an isEncrypted attribute to the config value. I want it to work and look as dynamic as possible.
So far I am leaning towards using the len (128) as deciding factor, but there is always a remote chance of the unencrypted value also being this length.
Thanks in advance.
public static string encrypt(string text)
{
// Locals
var passphrase = "5ab394ed-3920-4932-8d70-9c1b08f4ba4e";
byte[] results;
var utf8 = new UTF8Encoding();
// Step 1. We hash the passphrase using MD5
// We use the MD5 hash generator as the result is a 128 bit byte array
// which is a valid length for the TripleDES encoder we use below
var hashProvider = new MD5CryptoServiceProvider();
var tdesKey = hashProvider.ComputeHash(utf8.GetBytes(passphrase));
// Step 2. Create a new TripleDESCryptoServiceProvider object
// Step 3. Setup the encoder
var tdesAlgorithm = new TripleDESCryptoServiceProvider
{
Key = tdesKey,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
// Step 4. Convert the input string to a byte[]
var dataToEncrypt = utf8.GetBytes(text);
// Step 5. Attempt to encrypt the string
try
{
var encryptor = tdesAlgorithm.CreateEncryptor();
results = encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
}
finally
{
// Clear the TripleDes and Hashprovider services of any sensitive information
tdesAlgorithm.Clear();
hashProvider.Clear();
}
// Step 6. Return the encrypted string as a base64 encoded string
return Convert.ToBase64String(results);
}
What you could do in the isEncrypted method is to try to decrypt the message.
Since you are using PKCS7 padding most likely an unencrypted message will fail to decrypt since the padding does not conform to the set padding mode.
The decryption will throw an exception and you'll have to catch this and return false in this case.
There is a remote chance that the decryption will go through (when the message is not encrypted) if the data conforms to the padding mode. This is however most unlikely.
What I would do in this case would be to add some kind of flag in the encrypted data or append some data to encrypted message since I can then remove it in the decryption. This would be the most foolproof way.
First, as a serious issue, it's an exceedingly poor idea to use cryptographic primitives on your own. You've chosen to use the Electronic Codebook mode of encryption, which has the property that identical plaintext blocks produce identical cyphertext blocks. Check out the example at Wikipedia.
That said, a simple solution is to prepend a token such as 'ENC:' to the encrypted password. If you need to worry about malicious tampering with the config file, you should proceed to use a message authentication code, such as HMAC.
As your function returns a string there's no reason you can't add a plaintext code to the beginning of the encrypted data that the IsEncrypted function can look for, say "MD5ENC"+ [ciphertext].
The disadvantage of this is that it will let anyone who has the raw string know what algorithm was used for encryption. But as we keep getting reminded security through obscurity is no security at all. Anyone should be allowed to know how something was encrypted and have no easy way of breaking that encryption.
Note my use of the word should.
Anyhow, to return to my original suggestion. The advantage of this is that the longer your introductory code on the string the more vanishingly tiny the chances of it being generated by accident in another unrelated Base64 encrypted string becomes.
Should the ciphertext need decrypting just snip off your standard length encryption ident code and away you go...
Related
I am developing an integration in C# which syncs Office365 distribution lists to Sendy (sendy.co), written in PHP.
In the PHP application some ID's are being encrypted and I want to achieve the same in C# so that I can communicate using their API without having to look up the 'secret' ID.
This is the code in PHP (I replaced the password) in their application that calculates these ID's:
$encrypted = openssl_encrypt($in, 'AES-256-CBC', 'API_KEY', 0, 'SECRET_PASSWORD');
$encrypted = str_replace('/', '892', $encrypted);
$encrypted = str_replace('+', '763', $encrypted);
$encrypted = str_replace('=', '', $encrypted);
I overcame this 'issue' by hosting the PHP script somewhere and calling it from my C# application, but I want to make it opensource so I would like this to be integrated in the application.
I suppose I would have to start with .NET's AesCryptoServiceProvider, but I don't seem to be able to get it right (I get exceptions about the key length and stuff).
So far I tried this:
public static string Execute()
{
// openssl_encrypt ( string $data , string $method , string $password [, int $options = 0 [, string $iv = "" ]] )
var aes = new AesCryptoServiceProvider();
aes.KeySize = 256;
// Fixed password in code
aes.Key = Encoding.UTF8.GetBytes("FIXED PASSWORD");
// API = IV
aes.IV = Encoding.UTF8.GetBytes("SENDY API KEY");
aes.Mode = CipherMode.CBC;
// Trying to encrypt "36" in this case
byte[] src = Encoding.Unicode.GetBytes("36");
// Actual encryption
using (var encrypt = aes.CreateEncryptor())
{
byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
// Convert byte array to Base64 strings
return Convert.ToBase64String(dest);
}
}
However this throws an exception saying the IV doesn't match the block size of the algorithm.
I suppose the openssl_encrypt method in PHP derivatives the actual IV from the given API KEY in the sample (so the $password parameter), but I can't find much documentation on it to be able to achieve the same in C#.
The size of the iv must be equal to the block size which for AES is 16-bytes, "SENDY API KEY" is only 13-bytes.
The iv should be a different random value for each encryption, just prepend it to the encrypted data for use during decryption.
Next you have specified a key size of 256-bits but the key "FIXED PASSWORD" is only 14-bytes, make them the same, 128, 192 or 256 bits (16, 24 or 32 bytes). There is no need to use a key over 128-bits.
A password should not be used directly for a key, the key should be derived from the password with a function such as PBKFD2.
AES is a block cipher and it's. Input needs to be a multiple of the block size in length. To accomplish this padding of the input is needed. Typically PKCS#7 (née PKCS#5) padding is used, it is probably the default for OpenSSL. The encryption/decryptions should automatically add/remove this padding. But this does mean that the encrypted data length will be from 1-byte to 16-bytes longer than the input. e.g. If you encrypt "36" the output length will be 16-bytes.
Getting all this together correctly can be difficult to get correct, consider using an overall solution such as RNCryptor-php or defuse
Once again I'm tasked with converting ColdFusion code used for a single sign-on to C# and am running short on time. This one is completely different than my question that was answered here, so I'm back to being in over my head.
The original ColdFusion code was executed in a <cfscript> tag. I've replaced the src and pwd variables with abbreviated placeholders just to obscure their actual values:
//create a key to be used
src="xxx";
pwd="abc";
// Base64 Decoding the key
base64Decoder = createObject("java", "sun.misc.BASE64Decoder");
desKeyData = base64Decoder.decodeBuffer(pwd);
// Initialize the constructor of DESedeKeySpec with private key
KeySpec=createObject("java", "javax.crypto.spec.DESedeKeySpec");
KeySpec=KeySpec.init(desKeyData);
// Generate the secret key using SecretKeyFactory
keyFac=createObject("java", "javax.crypto.SecretKeyFactory").getInstance("DESede");
secretKey =keyFac.generateSecret(KeySpec);
// Get CIPHER OBJ ready to use
decodecipher = createObject("java", "javax.crypto.Cipher").getInstance("DESede/ECB/PKCS5Padding");
decodecipher.init(2, secretKey);
encodecipher = createObject("java", "javax.crypto.Cipher").getInstance("DESede/ECB/PKCS5Padding");
encodecipher.init(1, secretKey);
stringBytes = toString(src).getBytes("UTF8");
raw = encodecipher.doFinal(stringBytes);
// Base64Encoding of generated cipher
cipherText=ToBase64(raw);
I also have a document from the other party that outlines the steps for creating the single sign-on as follows:
Creating the encrypted token
Create the plain text (this corresponds to the variable src above, and that part I've done successfully in C#)
Pad the plain text
Decode the key (the key corresponds to the variable pwd above, and must be base 64 decoded; I think I've successfully gotten up to this point as well.)
Perform the encryption (use the decoded key obtained above and the plain text to do the encryption)
Encode the cipher text (url encoded)
I have the BouncyCastle libraries installed and am trying to make use of those, but I'm stuck on the actual encryption step. So far the beginning of my C# conversion looks like this (once again the token and key have abbreviated placeholders to obscure the actual values):
//steps omitted here to create src string
string token = "xxx";
string key = "abc";
byte[] decodedKeyBytes = Convert.FromBase64String(key);
I know that's not a whole lot to go on, but I've tried so many things that haven't worked that I've lost track. Eventually when I get to the piece where I'm initializing the cipher, I assume I need something like this:
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new DesEdeEngine());
Thanks very much for any suggestions/examples.
Update:
Thanks to the very helpful answer below, I was able to get this working using the following code:
string token = "xxx";
string key = "abc";
byte[] base64DecodedKeyBytes = Convert.FromBase64String(key);
byte[] inputBytesToken = System.Text.Encoding.UTF8.GetBytes(token);
// initialize for EBC mode and PKCS5/PKCS7 padding
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new DesEdeEngine());
KeyParameter param = new KeyParameter(base64DecodedKeyBytes);
cipher.Init(true, param);
// encrypt and encode as base64
byte[] encryptedBytesToken = cipher.DoFinal(inputBytesToken);
string tokenBase64 = System.Convert.ToBase64String(encryptedBytesToken);
This one is completely different
Not so much ;-) You already answered your own question.
Do not let the java code throw you. Ignoring some unused variables, it is doing exactly the same thing as encrypt() on your other thread - except with "TripleDES" instead of "Blowfish". encrypt() hides a lot of the complexity, but internally it is does the same thing - using those same java classes FWIW. That means you can use the same C# code. As you already guessed, you just need to swap out the crypto engine:
....
// initialize for EBC mode and PKCS5/PKCS7 padding
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new DesEdeEngine());
...
Update:
Just to elaborate a bit, when you use encrypt( someUTF8String, base64Key, algorithm, encoding), CF performs the same steps as your java code internally:
Decodes the key from base64, and creates a KeySpec object for the given algorithm, ie
// Base64 Decoding the key
// CF may use a different decoder, but the overall process is the same
base64Decoder = createObject("java", "sun.misc.BASE64Decoder");
....
secretKey =keyFac.generateSecret(KeySpec);
Next it extracts the UTF-8 bytes of the plain text, ie
stringBytes = toString(src).getBytes("UTF8");
CF then creates a cipher, which pads and encrypts the plain text, ie:
encodeCipher = createObject("java", "javax.crypto.Cipher").getInstance(algorithm);
encodeCipher.init(1, secretKey); // 1 - ENCRYPT_MODE
raw = encodeCipher.doFinal(stringBytes);
Finally, CF encodes the encrypted bytes as base64, ie:
cipherText=ToBase64(raw);
So as you can see, the java code and encrypt do exactly the same thing.
I am currently using AesManaged class in C# to encrypt a plain text. It works fine.
However, it produces the same cipher text each time it encrypts same piece of data. Is there anyway I can tweak this behavior and produce different cipher text for same piece of data?
I have implemented encryption in SQL server using AES_256 algorithm and certificate. The process closely resembles with the post here: http://www.codeproject.com/Articles/662187/FIPS-Encryption-Algorithms-and-Implementation-of-A. In this process each time a plain text is encrypted, different cipher text is produced.
I want the same effect with C# code. How that can be achieved?
EDIT:
Here is how I implemented the approach suggested by Yolanda Ruiz:
Encrypt
public static string Encrypt(string plainText)
{
//Check for valid arguments.
if (String.IsNullOrEmpty(plainText)) throw new ArgumentNullException("plainText");
List<byte> encryptedList;
//Create Aes object
using (AesManaged aes = new AesManaged())
{
aes.Key = Key;
aes.GenerateIV();
encryptedList = aes.IV.ToList();
aes.BlockSize = BlockSize;
/*Here goes the standard code to encrypt the plain text - refer msdn for that*/
/*Append the encrypted stream to encryptedList*/
}
return encryptedList.ToArray().ToBase64();
}
Decrypt
public static string Decrypt(string cipherText)
{
//Check for valid arguments.
if (string.IsNullOrEmpty(cipherText)) throw new ArgumentNullException("cipherText");
string plainText;
byte[] cipherTextArray = cipherText.FromBase64();
//Create Aes object
using (AesManaged aes = new AesManaged())
{
aes.Key = Key;
aes.BlockSize = BlockSize;
aes.IV = cipherTextArray.Take(NoOfBytes).ToArray();//Extract the IV
cipherTextArray = cipherTextArray.Skip(NoOfBytes).ToArray();//Extract the actual plain text.
/*Here goes the standard code to Decrypt the cipher text - refer msdn for that*/
/*Assign the decrypted stream output to plainText*/
}
return plainText;
}
Unit Test
//Arrange
string plainText = "Sayan";
//Act
string cipherText1 = MyCrypto.Encrypt(plainText);
string cipherText2 = Crypto.Encrypt(plainText);
string plainText1 = Crypto.Decrypt(cipherText1);
string plainText2 = Crypto.Decrypt(cipherText2);
//Assert
//Check the cipher text is different everytime
Assert.AreNotEqual(cipherText1, cipherText2);
//Check that every plaintext output should match with the original
Assert.AreEqual(plainText, plainText1);
Assert.AreEqual(plainText, plainText2);
The way to do that is to use a different Initialization Vector for each encryption.
The default mode of operation in AesManaged is CBC. In this mode, when a block of plaintext is encrypted, it is first mixed with the result of the encryption of the previous block. As long as the previous ciphertext block is always different, this prevents two similar blocks of plaintext to output the same ciphertext. But what do we use for the very first block then? The initialization vector.
The IV is basically a randomized block that acts as if it was the result of encrypting an hypothetical plaintext block coming before the actual first block of plaintext.
The IV has to be kept around so we can feed it to the decryption method. As it is semantically a ciphertext block, it is usual to prepend it to the actual ciphertext. When decrypting, you would first extract the first block of ciphertext (as is, without decrypting) and use it as the IV to decrypt subsequent blocks.
The IV is not a secret. The attacker will not be able to derive the key or the first plaintext block from it. You must never reuse the same IV twice with the same key though, or you loose the randomization property.
The methods you will want to look at are AesManaged.GenerateIV(), AesManaged.BlockSize (which is in bits, keep it in mind if you use that property to extract the IV bytes from the ciphertext).
Encryption algorithms have to be deterministic (otherwise there's no way of reversing them)
If you want to get different cipher text, you'll have to change the key, or the data to be encrypted (or the actual algorithm).
Ive been having some Crypto troubles cant see find what I've done wrong. I'm trying to encrypt an AESkey using RSA on Android and Decrypt it server side using C#, but keep getting a "Bad Data" exception.
I used Base64encoding to move the encrypted key from client to server and noticed that after moving it from the client(Android App) using a JSON POST request there were a number of "\u000a" in the key making the encrypted data length 941 which led to a "Data to large for decryption" when removed in brought the length to 920 which allowed for 80 8 byte iterations and got me to where I am now with the Bad Data problem.
I have checked that the key Length and Algorithm are correct and both are set for 2048 bit key and using PKCS1Padding.
"Bad Data" Exception
This exception will be thrown in the following scenarios.
a) The RSA private key used for decryption does not match with the RSA public key that is used for encryption.
b) The binary data passed in to Decrypt() method is incorrect. This could happen if the application code made assumptions about the length of encrypted data or the data passed in does not match the exact bytes that is returned from Encrypt() method.
I get the public key on android by pulling it from the server with a GET which returns RSACryptoServiceProvider.ToXMLString(false); And use the same keystore for the private key so cant see it being 1.
And as far as I know the c# decrypter Isn't making any assumptions about the size of the encrypted data. Possibly my setting block size to 8 but thats after i knew the size of the encrypted AESkey.
I've been looking around for a solution and couldn't find one so would be grateful for any assistance. Apologies if I'm being stupid and missed something simple but I have my blinkers on if I am and just cant see it.
Java Encryption
private byte[] encryptRSA(byte [] data) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
//instance of singleton PublicKey
AppPublicKey currKey = AppPublicKey.getInstance();
Log.d("ENCRYPT.MOD: ", currKey.getModBytes().toString());
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(new BigInteger(1,currKey.getModBytes()), new BigInteger(1,currKey.getExpBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(data);
Log.d("RSAENCRYPTION: ",Base64.encodeToString(cipherData, 1));
return cipherData;
}
C# Decrypt
public string DecryptString(string inputString, int dwKeySize)
{
// TODO: Add Proper Exception Handlers
CspParameters cp = new CspParameters();
cp.KeyContainerName = "real_Keystore";
RSACryptoServiceProvider rsaCryptoServiceProvider
= new RSACryptoServiceProvider(dwKeySize,cp);
int base64BlockSize = 8;
int iterations = inputString.Length / base64BlockSize;
ArrayList arrayList = new ArrayList();
for (int i = 0; i < iterations; i++)
{
byte[] encryptedBytes = Convert.FromBase64String(
inputString.Substring(base64BlockSize * i, base64BlockSize));
//Array.Reverse(encryptedBytes);
arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(
encryptedBytes, false));
}
return Encoding.UTF32.GetString(arrayList.ToArray(
Type.GetType("System.Byte")) as byte[]);
}
It is not possible to feed a few bytes at a time to the RSA operation.
Furthermore it seems unlikely that the code performs the right amount of base 64 iterations (as you defined NO_PADDING for base 64 in your android, using 1 instead of the constant). Normally the output of RSA encryption won't be a multiple of 3 bytes, so you are at least one block off the mark.
You may want to take a closer look at the API functions you are using and take some time to study RSA examples on .NET. Normally RSA is only used to encrypt small amounts of data (such as symmetric data encryption keys) so you should be able to decode all of the base64 data in one go.
Please test your input and output in a debugger. Encryption/decryption problems normally require that the exact input and output of the encryption/decryption algorithms are compared .
A bit more background info as suggested:
I'm finsihing of an Intranet CMS web app where I have to use the products API (ASP.NET based). Because of time constraints and issues with Windows authen' I need another way to ensure staff do not need to re login everytime they visit the site to view personalised content. The way it works is that once a user logs in (username/password), a Session ID storing a new different Security context value is generated that is used to display the personalised content. The API login method called uses the username and password as parameters. The only way I can think of automatically logging in the next time the staff visits the site is by storing the password in a enrypted cookie and checking of its existing when the site is visited and then calling the API login method using the username and decrypted password cookie values.
Any other ideas as an alternative welcomed.
Mo
Hi,
I'm using some code found on the web to encrypt and decrypt a password string. It encrypts fine but when it calls the code below to decrypt the string it throws the error "Length of the data to decrypt is invalid" How can I resolve this?
Thanks in advance.
Mo
System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] myByteArray = enc.GetBytes(_pword);
SymmetricAlgorithm sa = DES.Create();
MemoryStream msDecrypt = new MemoryStream(myByteArray);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, sa.CreateDecryptor(), CryptoStreamMode.Read);
byte[] decryptedTextBytes = new Byte[myByteArray.Length];
csDecrypt.Read(decryptedTextBytes, 0, myByteArray.Length);
csDecrypt.Close();
msDecrypt.Close();
string decryptedTextString = (new UnicodeEncoding()).GetString(decryptedTextBytes);
A couple of things here...
You shouldn't encrypt passwords usually. You should hash them.
If you decide to continue down the road of encryption..
You are using the DES algorithm. This is considered insecure and flawed. I'd recommend looking at the AES algorithm.
Depending on how much data you are working with, the CryptoStream might be overkill.
Using the ASCII encoding can cause loss of data that isn't ASCII, like Cyrillic letters. The recommended fix is to use something else, like UTF8.
Here is an example:
string text = "Hello";
using (var aes = new AesManaged())
{
var bytes = System.Text.Encoding.UTF8.GetBytes(text);
byte[] encryptedBytes;
using (var encrypt = aes.CreateEncryptor())
{
encryptedBytes = encrypt.TransformFinalBlock(bytes, 0, bytes.Length);
}
byte[] decryptedBytes;
using (var decrypt = aes.CreateDecryptor())
{
decryptedBytes = decrypt.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
}
var decryptedText = System.Text.Encoding.UTF8.GetString(decryptedBytes);
Console.Out.WriteLine("decryptedText = {0}", decryptedText);
}
This will use a random key every time. It is likely that you will need to encrypt some data, then decrypt it at a later time. When you create the AesManaged object, you can store the Key and IV property. You can re-use the same Key if you'd like, but different data should always be encrypted with a different IV (Initialization Vector). Where you store that key, is up to you. That's why hashing might be a better alternative: there is no key, and no need to worry about storing the key safely.
If you want to go down the hashing route, here is a small example:
var textToHash = "hello";
using (SHA1 sha = new SHA1Managed())
{
var bytesToHash = System.Text.Encoding.UTF8.GetBytes(textToHash);
var hash = sha.ComputeHash(bytesToHash);
string base64hash = Convert.ToBase64String(hash);
}
This uses the SHA1 algorithm, which should work fine for passwords, however you may want to consider SHA256.
The concept is simple: a hash will produce a (mostly) unique output for an input, however the output cannot be converted back to the input - it's destructive. Whenever you want to check if a user should be authenticated, check hash the password they gave you, and check it against the hash of the correct password. That way you aren't storing anything sensitive.
I've actually had this error before and it took me 3 days to figure out the solution. The issue will be the fact that the machine key you need for descryption needs to be registered on your machine itself.
Read fully up on DES encryption, it works by an application key, and a machine-level key. The error you're getting is likely because of the machine key missing.
Compare the bytes used to create the _pword string (in the encryption method) to the bytes retrieved with GetBytes. Probably you will notice a change in the data there.
To store the encrypted bytes, I think you should use Convert.ToBase64String and Convert.FromBase64String turn the encrypted password to/from a string.
I also do not see the code where you set the Key and IV. So I guess you are using a different key to encrypt and decrypt the password.
If the current Key property is null,
the GenerateKey method is called to
create a new random Key. If the
current IV property is null, the
GenerateIV method is called to create
a new random IV.
DES is a block based cipher - only certain lengths of buffers are valid. If I remember correctly, the block size for DES is 64 bits, so you need to ensure that your byte array is a multiple of 8 bytes long.
(That should fix your immediate problem, but I'd reference other peoples advice here - you really ought not to be using DES for any new code, and for passwords it's usually more appropriate to hash than to encrypt).