I am working on re-writing our encryption class to be FIPS compliant, and in doing so have to re-work how we're handling non-secret payload data. At the moment, I'm writing out the size of my non-secret payload, then writing the size of my IV. I follow that up by writing my non-secret payload and IV, with all of these writes sharing a BinaryWriter. Lastly, I then share the same MemoryStream and write my the data needing to be encrypted into the the CryptoStream.
This is what the class currently looks like:
public class Encryption
{
private const int SaltBlockSize = 8;
private const int SaltBitSize = 64;
private const int KeyBitSize = 256;
private const int SaltIterations = 10000;
private const int nonSecretPayloadOffsetInPayload = 0;
private const int ivOffsetInPayload = 1;
public byte[] GetNonSecretPayload(byte[] completePayload)
{
byte[] nonSecretPayload;
using (var memoryStream = new MemoryStream(completePayload))
{
using (var binaryReader = new BinaryReader(memoryStream))
{
int nonSecretPayloadLength = binaryReader.ReadInt32();
binaryReader.BaseStream.Position = 3;
nonSecretPayload = binaryReader.ReadBytes(nonSecretPayloadLength);
}
}
return nonSecretPayload;
}
public byte[] EncryptMessageWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null)
{
if (string.IsNullOrEmpty(password))
{
throw new InvalidOperationException("You can not provide an empty password, you must give a string that is at least 12 characters in size. If you just want to obfuscate the message without any protection, an alternative way is to use a Base64 String");
}
else if (password.Length < 12)
{
throw new InvalidOperationException("The minimum size your password can be is 12 characters.");
}
byte[] saltHash;
byte[] saltKey = this.CreateSaltKeysFromPassword(password, 0, out saltHash);
byte[] encryptedValue = null;
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
aesProvider.Key = saltKey;
aesProvider.Mode = CipherMode.CBC;
aesProvider.Padding = PaddingMode.PKCS7;
aesProvider.GenerateIV();
using (MemoryStream memoryStream = new MemoryStream())
{
// Write our IV out first so we can pull the IV off later during decryption.
// The IV does not need to be encrypted, it is safe to store as as unencrypted buffer in the encrypted byte array.
using (BinaryWriter ivWriter = new BinaryWriter(memoryStream, Encoding.UTF8, true))
{
// The first two writes to the stream should be the size of the non-secret payload
// and the size of the IV. If no payload exists, then we write 0.
if (nonSecretPayload == null || nonSecretPayload.Length == 0)
{
ivWriter.Write(0);
}
else
{
ivWriter.Write(nonSecretPayload.Length);
}
ivWriter.Write(aesProvider.IV.Length);
// If we have a payload, write it out.
if (nonSecretPayload != null && nonSecretPayload.Length > 0)
{
ivWriter.Write(nonSecretPayload);
}
// Write the Initialization Vector.
ivWriter.Write(aesProvider.IV);
}
// Create our encryptor and write the secret message to the encryptor stream.
var encryptor = aesProvider.CreateEncryptor(saltKey, aesProvider.IV);
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(secretMessage, 0, secretMessage.Length);
cryptoStream.FlushFinalBlock();
}
// Get the non-secret payload, IV, payload and IV lengths and encrypted data back as an array of bytes.
encryptedValue = memoryStream.ToArray();
}
}
return encryptedValue;
}
public string EncryptMessageWithPassword(string secretMessage, string password, byte[] nonSecretPayLoad = null)
{
byte[] secreteMessageBytes = Encoding.UTF8.GetBytes(secretMessage);
byte[] encryptedMessage = this.EncryptMessageWithPassword(secreteMessageBytes, password, nonSecretPayLoad);
return Convert.ToBase64String(encryptedMessage);
}
private byte[] CreateSaltKeysFromPassword(string password, int nonSecretPayloadSize, out byte[] saltHash)
{
byte[] saltKey;
//Use Random Salt to prevent pre-generated weak password attacks.
using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / SaltBlockSize, SaltIterations))
{
// Get a generated salt derived from the user password, hashed n-times where n = SaltIterations
saltHash = generator.Salt;
//Generate Keys
saltKey = generator.GetBytes(KeyBitSize / SaltBlockSize);
}
return saltKey;
}
}
I would expect in my GetNonSecretPayload(byte[] payload); that by setting the position, or using binaryReader.BaseStream.Seek(2); to skip the IV length item, I would skip the IV size entry in the byte[] array and be able to read the bytes associated with the actual non-secret data. This doesn't work though, presumably because this isn't an array underneath the covers that I can just move to the next element in the array, skipping the IV length wrote out originally.
I have the following unit test.
[TestClass]
public class EncryptionTests
{
private const string _ContentToEncrypt = "This is a test to make sure the encryption Type actually encrypts the data right.";
private const string _Password = "EncryptedPassword1";
[TestMethod]
public void Extract_non_secret_payload_content_from_encrypted_string()
{
// Arrange
var encryption = new Encryption();
string nonSecretData = "My payload is not considered secret and can be pulled out of the payload without decrypting";
// Convert the secret and non-secret data into a byte array
byte[] payload = Encoding.UTF8.GetBytes(nonSecretData);
byte[] encodedBytes = Encoding.UTF8.GetBytes(_ContentToEncrypt);
// Encrypt the secret data while injecting the nonsecret payload into the encrypted stream.
byte[] encryptedValue = encryption.EncryptMessageWithPassword(encodedBytes, _Password, payload);
// Act
// Pull the non-secret payload out of the encrypted message - without having to decrypt it.
byte[] UnencryptedPayloadWithinEncryptedArray = encryption.GetNonSecretPayload(encryptedValue);
string payloadContent = Encoding.UTF8.GetString(UnencryptedPayloadWithinEncryptedArray);
// Assert
Assert.AreEqual(nonSecretData, payloadContent);
}
}
What I get with my current binaryReader.BaseStream.Position = 3 is
"\0\u0010\0\0\0My payload is not considered secret and can be pulled out of the payload without decry"
I've read and wrote data like this in the past using a BinaryWriter, but I've never had to seek through it in order to skip data. What am I doing wrong here?
Related
I have the following code to Encrypt/Decrypt PII data.
public static class Encryption
{
public static readonly int KeyLengthBits = 256; //AES Key Length in bits
public static readonly int SaltLength = 8; //Salt length in bytes
private static readonly RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
private const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes
private const int PBKDF2SubkeyLength = 256 / 8; // 256 bits
private const int SaltSize = 128 / 8; // 128 bits
public static string DecryptString(string ciphertext, string passphrase)
{
var inputs = ciphertext.Split(":".ToCharArray(), 3);
var iv = Convert.FromBase64String(inputs[0]); // Extract the IV
var salt = Convert.FromBase64String(inputs[1]); // Extract the salt
var ciphertextBytes = Convert.FromBase64String(inputs[2]); // Extract the ciphertext
// Derive the key from the supplied passphrase and extracted salt
byte[] key = DeriveKeyFromPassphrase(passphrase, salt);
// Decrypt
byte[] plaintext = DoCryptoOperation(ciphertextBytes, key, iv, false);
// Return the decrypted string
return Encoding.UTF8.GetString(plaintext);
}
public static string EncryptString(string plaintext, string passphrase)
{
var salt = GenerateRandomBytes(SaltLength); // Random salt
var iv = GenerateRandomBytes(16); // AES is always a 128-bit block size
var key = DeriveKeyFromPassphrase(passphrase, salt); // Derive the key from the passphrase
// Encrypt
var ciphertext = DoCryptoOperation(Encoding.UTF8.GetBytes(plaintext), key, iv, true);
// Return the formatted string
return String.Format("{0}:{1}:{2}", Convert.ToBase64String(iv), Convert.ToBase64String(salt), Convert.ToBase64String(ciphertext));
}
private static byte[] DeriveKeyFromPassphrase(string passphrase, byte[] salt, int iterationCount = 2000)
{
var keyDerivationFunction = new Rfc2898DeriveBytes(passphrase, salt, iterationCount); //PBKDF2
return keyDerivationFunction.GetBytes(KeyLengthBits / 8);
}
private static byte[] GenerateRandomBytes(int lengthBytes)
{
var bytes = new byte[lengthBytes];
rng.GetBytes(bytes);
return bytes;
}
// This function does both encryption and decryption, depending on the value of the "encrypt" parameter
private static byte[] DoCryptoOperation(byte[] inputData, byte[] key, byte[] iv, bool encrypt)
{
byte[] output;
using (var aes = new AesCryptoServiceProvider())
using (var ms = new MemoryStream())
{
var cryptoTransform = encrypt ? aes.CreateEncryptor(key, iv) : aes.CreateDecryptor(key, iv);
using (var cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
cs.Write(inputData, 0, inputData.Length);
output = ms.ToArray();
}
return output;
}
}
If I publish this code and encrypt data and then decrypt it, there's no problem. I correctly receive the unencrypted data. If I rebuild my application without making any changes, then publish it again without re-encrypting the data, (it's already encrypted at this point), I'm unable to decrypt it. It just returns the encrypted strings.
Why would re-publishing to the same server to this? Should I be using a different approach? If so, please recommend that different approach.
Thanks
I know this question has been asked before but the answer simply wasn't what I needed. I need to create a password protected text file. I don't mean to encrypt but just create a file with a simple text password. It would also be nice to find out how to open this file in C# as well.
Create a plain-text password protected file and open this file at a later time. All in C#.
Password protecting a text file that is not encrypted is not really possible. However, you can validate if your text file has been modified, so that you are aware it has been altered by someone.
The concept is simple. Use a password to encrypt or obfuscate a hash of the data (text file). You can the later check this hash against the current data and determine whether or not it matches. You will need to store this signature (encrypted hash) somewhere maybe in a file called (textfile.sig).
You can use the SHA1Managed .NET class to create the hash, and the TripleDESCryptoServiceProvider class to encrypt the resulting hash.
something like...
public string GetSignature(string text, string password)
{
byte[] key;
byte[] key2;
GetKeys(password, out key, out key2);
string sig = encryptstring(GetSHA1(text), key, key2);
}
public void GetKeys(string password, out byte[] key, out byte[] key2)
{
byte[] data = StringToByte(password);
SHA1 sha = new SHA1CryptoServiceProvider();
MD5 md5 = new MD5CryptoServiceProvider();
byte[] hash1 = sha.ComputeHash(data);
byte[] hash2 = md5.ComputeHash(data);
// Generate some key data based on the supplied password;
byte[] key = new byte[24];
for (int i = 0; i < 20; i++)
{
key[i] = hash1[i];
}
for (int i = 0; i < 4; i++)
{
key[i + 20] = hash2[i];
}
byte[] key2 = new byte[8];
for (int i = 0; i < 8; i++)
{
key2[i] = hash2[i+4];
}
}
public string GetSHA1(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
SHA1Managed hashString = new SHA1Managed();
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
public string ByteToString(byte[] buff)
{
string sbinary = "";
for (int i = 0; i < buff.Length; i++)
{
sbinary += buff[i].ToString("X2"); // hex format
}
return (sbinary);
}
public string encryptstring(string instr, byte[] key, byte[] key2)
{
TripleDES threedes = new TripleDESCryptoServiceProvider();
threedes.Key = key;
threedes.IV = key2;
ICryptoTransform encryptor = threedes.CreateEncryptor(key, key2);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
// Write all data to the crypto stream and flush it.
csEncrypt.Write(StringToByte(instr), 0, StringToByte(instr).Length);
csEncrypt.FlushFinalBlock();
return ByteToString(msEncrypt.ToArray());
}
public string decryptstring(string instr, byte[] key, byte[] key2)
{
if (string.IsNullOrEmpty(instr)) return "";
TripleDES threedes = new TripleDESCryptoServiceProvider();
threedes.Key = key;
threedes.IV = key2;
ICryptoTransform decryptor = threedes.CreateDecryptor(key, key2);
// Now decrypt the previously encrypted message using the decryptor
MemoryStream msDecrypt = new MemoryStream(HexStringToByte(instr));
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
try
{
return ByteToString(csDecrypt);
}
catch (CryptographicException)
{
return "";
}
}
Otherwise, you will if you want to hide the data from people, you need to encrypt the data in the text file. You can do this by calling encryptstring() with the full text data instead of the hash of the data.
Whole point of the question was to not have to encrypt the data manually but let Windows deal with it so I decided to go with Hans Passant's suggestion and simply use a password protected zip file with the needed information (txt files) inside it. This can be easily done with DotNetZip.
This is my first post, so hope I haven't missed anything important. I'm doing a project in C# where I need to use public/private key encryption to encrypt a message and then send it over an SSL connection.
I chose to use the RSACryptoService, as according to the documentation, that was the only asymmetric encryption scheme used for encrypting data. The problem is that I am having a lot of problems with this. (I wanted to do symmetric encryption, but that is not what my teacher want me to do, and according to him it should be easy to just determine a block size and then it should do all the work for you.) Well, so far no luck and I've tried some different approaches, but now I'm back to basics and trying again, this is my current code:
public string[] GenerateKeysToStrings(string uniqueIdentifier)
{
string[] keys;
using (var rsa = new RSACryptoServiceProvider(4096))
{
try
{
string privateKey = rsa.ToXmlString(true);
string publicKey = rsa.ToXmlString(false);
this.pki.StoreKey(publicKey, uniqueIdentifier);
keys = new string[2];
keys[0] = privateKey;
keys[1] = publicKey;
}
finally
{
//// Clear the RSA key container, deleting generated keys.
rsa.PersistKeyInCsp = false;
}
}
return keys;
}
As you can see, I generate the keys and I mimmick a PKI by sending the public key to a simple class that stores it, and then the private key is written to a file
(Notice that I also have another method that does the same but stores it to an array instead, just because I wanted to test and simplify things as I get No such key exceptions and sometimes cryptographic exceptions when I do it the way shown in the example, so I wanted to simplify it by simply storing the rsa.ToXmlString string, as a string in an array, but no luck.)
Now I have an encrypt and decrypt method as follows:
public string Encrypt(string keyString, string message)
{
string encryptedMessage;
using (var rsa = new RSACryptoServiceProvider())
{
try
{
//// Load the key from the specified path
var encryptKey = new XmlDocument();
encryptKey.Load(#"C:\Test\PrivateKeyInfo.xml");
rsa.FromXmlString(encryptKey.OuterXml);
//// Conver the string message to a byte array for encryption
//// var encoder = new UTF8Encoding();
ASCIIEncoding byteConverter = new ASCIIEncoding();
byte[] dataToEncrypt = byteConverter.GetBytes(message);
byte[] encryptedData = rsa.Encrypt(dataToEncrypt, false);
//// Convert the byte array back to a string message
encryptedMessage = byteConverter.GetString(encryptedData);
}
finally
{
//// Clear the RSA key container, deleting generated keys.
rsa.PersistKeyInCsp = false;
}
}
return encryptedMessage;
}
Decryption:
public string Decrypt(string keyString, string message)
{
string decryptedText;
using (var rsa = new RSACryptoServiceProvider())
{
try
{
//// Loads the keyinfo into the rsa parameters from the keyfile
/*
var privateKey = new XmlDocument();
privateKey.Load(keyString);
*/
rsa.FromXmlString(keyString);
//// Convert the text from string to byte array for decryption
ASCIIEncoding byteConverter = new ASCIIEncoding();
var encryptedBytes = byteConverter.GetBytes(message);
//// Create an aux array to store all the encrypted bytes
byte[] decryptedBytes = rsa.Decrypt(encryptedBytes, false);
decryptedText = byteConverter.GetString(decryptedBytes);
}
finally
{
//// Clear the RSA key container, deleting generated keys.
rsa.PersistKeyInCsp = false;
}
}
return decryptedText;
}
I know that this is a wall of text, but I hope you can help me out because I've been banging my head against the wall for so long now it's not funny :)
The problem is, how do I go about encrypting messages with RSA (or any other public/private key encryption)
Here is the Test client:
public static void Main(string[] args)
{
PublicKeyInfrastructure pki = new PublicKeyInfrastructure();
Cryptograph crypto = new Cryptograph();
string[] keys = crypto.GenerateKeysToStrings("simonlanghoff#gmail.com");
string plainText = "Hello play with me, please";
string publicKey = crypto.GetPublicKey("simonlanghoff#gmail.com");
string encryptedText = crypto.Encrypt(keys[0], plainText);
string decryptedText = crypto.Decrypt(keys[1], encryptedText);
}
As I mentioned, the string arrays are there because I wanted to eliminate bad parsing error from XML documents...
When I run the test client, if I use the private key to encrypt and public key to decrypt, I get a "Key does not exist exception" and if I do it the other way around, I get a bad data exception.
Please help me out guys, if you know of any good guide, or can tell me how to somewhat straightfoward implement public/private key encryption on string messages, please help me out.
I appreciate any help.
This is not how RSA encryption should be done.
RSA is all about math. What you encrypt is a number so it has to be of finite length and matching the RSA keypair length you're using. Further length limitations are imposed by the padding used (either PKCS#1 or OAEP).
If you want to encrypt large data with RSA you need to do it indirectly - i.e. use a symmetric key to encrypt the large data and encrypt this key using the RSA public key.
You can read about implementing this on my blog.
Okay, I've finally come up with a solution to the problem I stated in my original post. This is something I haven't thoroughly tested or anything, but something I figured out from a little trial and error process.
Here is the current code I have:
public static string Encrypt(string dataToEncrypt, RSAParameters publicKeyInfo)
{
//// Our bytearray to hold all of our data after the encryption
byte[] encryptedBytes = new byte[0];
using (var RSA = new RSACryptoServiceProvider())
{
try
{
//Create a new instance of RSACryptoServiceProvider.
UTF8Encoding encoder = new UTF8Encoding();
byte[] encryptThis = encoder.GetBytes(dataToEncrypt);
//// Importing the public key
RSA.ImportParameters(publicKeyInfo);
int blockSize = (RSA.KeySize / 8) - 32;
//// buffer to write byte sequence of the given block_size
byte[] buffer = new byte[blockSize];
byte[] encryptedBuffer = new byte[blockSize];
//// Initializing our encryptedBytes array to a suitable size, depending on the size of data to be encrypted
encryptedBytes = new byte[encryptThis.Length + blockSize - (encryptThis.Length % blockSize) + 32];
for (int i = 0; i < encryptThis.Length; i += blockSize)
{
//// If there is extra info to be parsed, but not enough to fill out a complete bytearray, fit array for last bit of data
if (2 * i > encryptThis.Length && ((encryptThis.Length - i) % blockSize != 0))
{
buffer = new byte[encryptThis.Length - i];
blockSize = encryptThis.Length - i;
}
//// If the amount of bytes we need to decrypt isn't enough to fill out a block, only decrypt part of it
if (encryptThis.Length < blockSize)
{
buffer = new byte[encryptThis.Length];
blockSize = encryptThis.Length;
}
//// encrypt the specified size of data, then add to final array.
Buffer.BlockCopy(encryptThis, i, buffer, 0, blockSize);
encryptedBuffer = RSA.Encrypt(buffer, false);
encryptedBuffer.CopyTo(encryptedBytes, i);
}
}
catch (CryptographicException e)
{
Console.Write(e);
}
finally
{
//// Clear the RSA key container, deleting generated keys.
RSA.PersistKeyInCsp = false;
}
}
//// Convert the byteArray using Base64 and returns as an encrypted string
return Convert.ToBase64String(encryptedBytes);
}
/// <summary>
/// Decrypt this message using this key
/// </summary>
/// <param name="dataToDecrypt">
/// The data To decrypt.
/// </param>
/// <param name="privateKeyInfo">
/// The private Key Info.
/// </param>
/// <returns>
/// The decrypted data.
/// </returns>
public static string Decrypt(string dataToDecrypt, RSAParameters privateKeyInfo)
{
//// The bytearray to hold all of our data after decryption
byte[] decryptedBytes;
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
try
{
byte[] bytesToDecrypt = Convert.FromBase64String(dataToDecrypt);
//// Import the private key info
RSA.ImportParameters(privateKeyInfo);
//// No need to subtract padding size when decrypting (OR do I?)
int blockSize = RSA.KeySize / 8;
//// buffer to write byte sequence of the given block_size
byte[] buffer = new byte[blockSize];
//// buffer containing decrypted information
byte[] decryptedBuffer = new byte[blockSize];
//// Initializes our array to make sure it can hold at least the amount needed to decrypt.
decryptedBytes = new byte[dataToDecrypt.Length];
for (int i = 0; i < bytesToDecrypt.Length; i += blockSize)
{
if (2 * i > bytesToDecrypt.Length && ((bytesToDecrypt.Length - i) % blockSize != 0))
{
buffer = new byte[bytesToDecrypt.Length - i];
blockSize = bytesToDecrypt.Length - i;
}
//// If the amount of bytes we need to decrypt isn't enough to fill out a block, only decrypt part of it
if (bytesToDecrypt.Length < blockSize)
{
buffer = new byte[bytesToDecrypt.Length];
blockSize = bytesToDecrypt.Length;
}
Buffer.BlockCopy(bytesToDecrypt, i, buffer, 0, blockSize);
decryptedBuffer = RSA.Decrypt(buffer, false);
decryptedBuffer.CopyTo(decryptedBytes, i);
}
}
finally
{
//// Clear the RSA key container, deleting generated keys.
RSA.PersistKeyInCsp = false;
}
}
//// We encode each byte with UTF8 and then write to a string while trimming off the extra empty data created by the overhead.
var encoder = new UTF8Encoding();
return encoder.GetString(decryptedBytes).TrimEnd(new[] { '\0' });
}
As I said, I have not tested it much, other than sizes below, at and above the block-size, but it seems to be doing what it should. I am still a novice, so I would really like for you to scrutinize my code :)
Maybe I'm missing something, but it looks like your Encrypt() function doesn't make use of either the keyString parameter or the contents of encryptKey.
I want to obfuscate one query string parameter in ASP.NET. The site will have a high volume of request, so the algorithm shouldn't be too slow.
My problem is that all the algorithms I found result in unwanted characters (like +/=)
Here is an example of what i want to achieve:
www.domain.com/?id=1844
to
www.domain.com/?id=3GQ5DTL3oVd91WsGj74gcQ
The obfuscated param should only include a-z and A-Z and 0-9 characters.
I know I can encrypt using base64, but this will generate unwanted characters such as / or = or +.
Any idea what algorithm can be used?
Update:
I'm aware of UrlEncoding , i want to avoid encoding the string.
because that will generate charaters like %F2 or %B2 in the url.
You can use triple DES to encode the value using a narow block cipher.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace ConsoleApplication1 {
class Program {
static string ToHex(byte[] value) {
StringBuilder sb = new StringBuilder();
foreach (byte b in value)
sb.AppendFormat("{0:x2}", b);
return sb.ToString();
}
static string Encode(long value, byte[] key) {
byte[] InputBuffer = new byte[8];
byte[] OutputBuffer;
unsafe {
fixed (byte* pInputBuffer = InputBuffer) {
((long*)pInputBuffer)[0] = value;
}
}
TripleDESCryptoServiceProvider TDes = new TripleDESCryptoServiceProvider();
TDes.Mode = CipherMode.ECB;
TDes.Padding = PaddingMode.None;
TDes.Key = key;
using (ICryptoTransform Encryptor = TDes.CreateEncryptor()) {
OutputBuffer = Encryptor.TransformFinalBlock(InputBuffer, 0, 8);
}
TDes.Clear();
return ToHex(OutputBuffer);
}
static long Decode(string value, byte[] key) {
byte[] InputBuffer = new byte[8];
byte[] OutputBuffer;
for (int i = 0; i < 8; i++) {
InputBuffer[i] = Convert.ToByte(value.Substring(i * 2, 2), 16);
}
TripleDESCryptoServiceProvider TDes = new TripleDESCryptoServiceProvider();
TDes.Mode = CipherMode.ECB;
TDes.Padding = PaddingMode.None;
TDes.Key = key;
using (ICryptoTransform Decryptor = TDes.CreateDecryptor()) {
OutputBuffer = Decryptor.TransformFinalBlock(InputBuffer, 0, 8);
}
TDes.Clear();
unsafe {
fixed (byte* pOutputBuffer = OutputBuffer) {
return ((long*)pOutputBuffer)[0];
}
}
}
static void Main(string[] args) {
long NumberToEncode = (new Random()).Next();
Console.WriteLine("Number to encode = {0}.", NumberToEncode);
byte[] Key = new byte[24];
(new RNGCryptoServiceProvider()).GetBytes(Key);
Console.WriteLine("Key to encode with is {0}.", ToHex(Key));
string EncodedValue = Encode(NumberToEncode, Key);
Console.WriteLine("The encoded value is {0}.", EncodedValue);
long DecodedValue = Decode(EncodedValue, Key);
Console.WriteLine("The decoded result is {0}.", DecodedValue);
}
}
}
The output should be something like this:
Number to encode = 873435734.
Key to encode with is 38137b6a7aa49cc6040c4297064fdb4461c79a895f40b4d1.
The encoded value is 43ba3fb809a47b2f.
The decoded result is 873435734.
Note that the encoded value is only 16 characters wide.
If you're really conserned about abuse, then AES can be used in a similar manner. In the next example I switch in AES and write the 64 bit id number into both sides of the block. If it doesn't decode with the same value on both sides then it is rejected. This can prevent people from writing in random numbers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace ConsoleApplication1 {
class Program {
static string ToHex(byte[] value) {
StringBuilder sb = new StringBuilder();
foreach (byte b in value)
sb.AppendFormat("{0:x2}", b);
return sb.ToString();
}
static string Encode(long value, byte[] key) {
byte[] InputBuffer = new byte[16];
byte[] OutputBuffer;
unsafe {
fixed (byte* pInputBuffer = InputBuffer) {
((long*)pInputBuffer)[0] = value;
((long*)pInputBuffer)[1] = value;
}
}
AesCryptoServiceProvider Aes = new AesCryptoServiceProvider();
Aes.Mode = CipherMode.ECB;
Aes.Padding = PaddingMode.None;
Aes.Key = key;
using (ICryptoTransform Encryptor = Aes.CreateEncryptor()) {
OutputBuffer = Encryptor.TransformFinalBlock(InputBuffer, 0, 16);
}
Aes.Clear();
return ToHex(OutputBuffer);
}
static bool TryDecode(string value, byte[] key, out long result) {
byte[] InputBuffer = new byte[16];
byte[] OutputBuffer;
for (int i = 0; i < 16; i++) {
InputBuffer[i] = Convert.ToByte(value.Substring(i * 2, 2), 16);
}
AesCryptoServiceProvider Aes = new AesCryptoServiceProvider();
Aes.Mode = CipherMode.ECB;
Aes.Padding = PaddingMode.None;
Aes.Key = key;
using (ICryptoTransform Decryptor = Aes.CreateDecryptor()) {
OutputBuffer = Decryptor.TransformFinalBlock(InputBuffer, 0, 16);
}
Aes.Clear();
unsafe {
fixed (byte* pOutputBuffer = OutputBuffer) {
//return ((long*)pOutputBuffer)[0];
if (((long*)pOutputBuffer)[0] == ((long*)pOutputBuffer)[1]) {
result = ((long*)pOutputBuffer)[0];
return true;
}
else {
result = 0;
return false;
}
}
}
}
static void Main(string[] args) {
long NumberToEncode = (new Random()).Next();
Console.WriteLine("Number to encode = {0}.", NumberToEncode);
byte[] Key = new byte[24];
(new RNGCryptoServiceProvider()).GetBytes(Key);
Console.WriteLine("Key to encode with is {0}.", ToHex(Key));
string EncodedValue = Encode(NumberToEncode, Key);
Console.WriteLine("The encoded value is {0}.", EncodedValue);
long DecodedValue;
bool Success = TryDecode(EncodedValue, Key, out DecodedValue);
if (Success) {
Console.WriteLine("Successfully decoded the encoded value.");
Console.WriteLine("The decoded result is {0}.", DecodedValue);
}
else
Console.WriteLine("Failed to decode encoded value. Invalid result.");
}
}
}
The result should now look something like this:
Number to encode = 1795789891.
Key to encode with is 6c90323644c841a00d40d4407e23dbb2ab56530e1a4bae43.
The encoded value is 731fceec2af2fcc2790883f2b79e9a01.
Successfully decoded the encoded value.
The decoded result is 1795789891.
Also note that since we have now used a wider block cipher the encoded value is now 32 characters wide.
You can use HttpServerUtility.UrlTokenEncode and HttpServerUtility.UrlTokenDecode
Encode uses base64 encoding, but replaces URL unfriendly characters.
There's a similar answer in a previous SO question. See the accepted answer.
So here's a working example that I put together from a few different examples that takes an integer ID and converts it to a hexidecimal formatted encrypted string. This encrypted string should not include URL-unfriendly characters and will not include escaped characters either.
Here's the entire working console app. Please note that it's a prototype and definitely not for production -- this just illustrates a solution and definitely needs to be refactored.
When you run the code, your output should be this:
1234 get encrypted as ZaB5GE/bWMJcNaeY/xJ6PQ==
ZaB5GE/bWMJcNaeY/xJ6PQ== encrypted is this in hex 5a61423547452f62574d4a634e6165592f784a3650513d3d
5a61423547452f62574d4a634e6165592f784a3650513d3d gets dehexed as ZaB5GE/bWMJcNaeY/xJ6PQ==
ZaB5GE/bWMJcNaeY/xJ6PQ== got decrypted as 1234
Sources:
byte to hex article on SO: Encryption to alphanumeric in System.Security.Cryptography
Crypto helper class: Encrypt and decrypt a string (4th answer)
Program2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace ConsoleApplication1
{
class Program2
{
static void Main(string[] args)
{
int theId = 1234; //the ID that's being manipulated
byte[] byteArray; //the byte array that stores
//convert the ID to an encrypted string using a Crypto helper class
string encryptedString = Crypto.EncryptStringAES(theId.ToString(), "mysecret");
Console.WriteLine("{0} get encrypted as {1}", theId.ToString(), encryptedString);
//convert the encrypted string to byte array
byteArray = ASCIIEncoding.Default.GetBytes(encryptedString);
StringBuilder result = new StringBuilder();
//convert each byte to hex and append to a stringbuilder
foreach (byte outputByte in byteArray)
{
result.Append(outputByte.ToString("x2"));
}
Console.WriteLine("{0} encrypted is this in hex {1}", encryptedString, result.ToString());
//now reverse the process, and start with converting each char in string to byte
int stringLength = result.Length;
byte[] bytes = new byte[stringLength / 2];
for (int i = 0; i < stringLength; i += 2)
{
bytes[i / 2] = System.Convert.ToByte(result.ToString().Substring(i, 2), 16);
}
//convert the byte array to de-"hexed" string
string dehexedString = ASCIIEncoding.Default.GetString(bytes);
Console.WriteLine("{0} gets dehexed as {1}", result, dehexedString);
//decrypt the de-"hexed" string using Crypto helper class
string decryptedString = Crypto.DecryptStringAES(dehexedString, "mysecret");
Console.WriteLine("{0} got decrypted as {1}", dehexedString, decryptedString);
Console.ReadLine();
}
}
public class Crypto
{
private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");
/// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.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);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
/// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
public static string DecryptStringAES(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
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();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
}
}
The problem with obfuscating the id, is that you need a way to de-obfuscicate. This requires either:
Fullblown encryption, which if it's any good will require a pretty large value.
Storing the value along with the id number, so it becomes an alternative identifier.
Something that depends on security-by-obscurity.
Alternatively, keep the id clear, but use a check as well.
public static String ChkSumStr(int id, int reduce)
{
return string.Concat(ReduceStrength(ChkSum(id), reduce).Select(b => b.ToString("X2")).ToArray());
}
public static byte[] ChkSum(int id)
{
byte[] idBytes = Encoding.UTF8.GetBytes("This is an arbitrary salt" + id);
return SHA256.Create().ComputeHash(idBytes);
}
private static byte[] ReduceStrength(byte[] src, int reduce)
{
byte[] ret = null;
for(int i = 0; i != reduce; ++i)
{
ret = new byte[src.Length / 2];
for(int j = 0; j != ret.Length; ++j)
{
ret[j] = (byte)(src[j * 2] ^ src[j * 2 + 1]);
}
src = ret;
}
return src;
}
The higher the value given for reduce, the smaller the result (until at 6 it keeps producing the empty string). A low value (or 0) gives better security, at the cost of a longer URI.
The string "This is an arbitrary salt" needs to be secret for best security. It can be hardcoded in some uses, but would want to be obtained from a secure source for others.
With the above, an id of 15 and a reduce of 3 produces a result of 05469B1E. We can then use this as:
www.domain.com/?id=15&chk=05469B1E
In the handler that would look up whatever 15 is, we do the same thing again, and if the result is different to 05469B1E we can either return a 403 Forbidden or arguably more reasonable 404 Not Found (on the basis that we've received a URI that as a whole doesn't identify anything).
Have you tried URL encoding your query string text? It's part of the HttpUtility class which:
Provides methods for encoding and
decoding URLs when processing Web
requests.
and should allow you to pass your base64 encoded text in the query string.
Do your encryption and then use HttpServerUtility.UrlTokenEncode() to encode the byte array.
I am building a iPhone app which uses c# web services. My c# web services takes user details and validates against my DB and returns xml files.
So Now the issue is how to encrypt user details(username and password are 10chars each) in objective c and decrypt in C#.
I am very new to cryptography, which method is the best. will it be possible to encrypt in Objective c and Decrypt in C#.
thanks..
Thanks for the rapid replies. I appreciate your help. I found a blog which explains my problem. Here is the link for it.
http://dotmac.rationalmind.net/2009/02/aes-interoperability-between-net-and-iphone/
I am implementing it now. I will let you know the status soon.
Thanks a lot..
Happy coding..
On the assumption that you're encrypting this information in order to protect it over the network, the best solution is to connect over SSL. This will address the problem without creating new complexities in the code. SSL handling is generally available in both .NET and Cocoa.
Is there some other reason that you're trying to encrypt this data?
The following is from the The CSharp Cookbook. It is about as straight forwand an example as exists. You would of course have to port the encrypt portion to Objective C, but so long as you used the same Key, it should generate the same result.
You need to use Rijndael cipher which is available here in ObjC compatible code
public static void EncDecString()
{
string encryptedString = CryptoString.Encrypt("MyPassword");
Console.WriteLine("encryptedString: " + encryptedString);
// get the key and IV used so you can decrypt it later
byte [] key = CryptoString.Key;
byte [] IV = CryptoString.IV;
CryptoString.Key = key;
CryptoString.IV = IV;
string decryptedString = CryptoString.Decrypt(encryptedString);
Console.WriteLine("decryptedString: " + decryptedString);
}
public sealed class CryptoString
{
private CryptoString() {}
private static byte[] savedKey = null;
private static byte[] savedIV = null;
public static byte[] Key
{
get { return savedKey; }
set { savedKey = value; }
}
public static byte[] IV
{
get { return savedIV; }
set { savedIV = value; }
}
private static void RdGenerateSecretKey(RijndaelManaged rdProvider)
{
if (savedKey == null)
{
rdProvider.KeySize = 256;
rdProvider.GenerateKey();
savedKey = rdProvider.Key;
}
}
private static void RdGenerateSecretInitVector(RijndaelManaged rdProvider)
{
if (savedIV == null)
{
rdProvider.GenerateIV();
savedIV = rdProvider.IV;
}
}
public static string Encrypt(string originalStr)
{
// Encode data string to be stored in memory
byte[] originalStrAsBytes = Encoding.ASCII.GetBytes(originalStr);
byte[] originalBytes = {};
// Create MemoryStream to contain output
MemoryStream memStream = new MemoryStream(originalStrAsBytes.Length);
RijndaelManaged rijndael = new RijndaelManaged();
// Generate and save secret key and init vector
RdGenerateSecretKey(rijndael);
RdGenerateSecretInitVector(rijndael);
if (savedKey == null || savedIV == null)
{
throw (new NullReferenceException(
"savedKey and savedIV must be non-null."));
}
// Create encryptor, and stream objects
ICryptoTransform rdTransform =
rijndael.CreateEncryptor((byte[])savedKey.Clone(),
(byte[])savedIV.Clone());
CryptoStream cryptoStream = new CryptoStream(memStream, rdTransform,
CryptoStreamMode.Write);
// Write encrypted data to the MemoryStream
cryptoStream.Write(originalStrAsBytes, 0, originalStrAsBytes.Length);
cryptoStream.FlushFinalBlock();
originalBytes = memStream.ToArray();
// Release all resources
memStream.Close();
cryptoStream.Close();
rdTransform.Dispose();
rijndael.Clear();
// Convert encrypted string
string encryptedStr = Convert.ToBase64String(originalBytes);
return (encryptedStr);
}
public static string Decrypt(string encryptedStr)
{
// Unconvert encrypted string
byte[] encryptedStrAsBytes = Convert.FromBase64String(encryptedStr);
byte[] initialText = new Byte[encryptedStrAsBytes.Length];
RijndaelManaged rijndael = new RijndaelManaged();
MemoryStream memStream = new MemoryStream(encryptedStrAsBytes);
if (savedKey == null || savedIV == null)
{
throw (new NullReferenceException(
"savedKey and savedIV must be non-null."));
}
// Create decryptor, and stream objects
ICryptoTransform rdTransform =
rijndael.CreateDecryptor((byte[])savedKey.Clone(),
(byte[])savedIV.Clone());
CryptoStream cryptoStream = new CryptoStream(memStream, rdTransform,
CryptoStreamMode.Read);
// Read in decrypted string as a byte[]
cryptoStream.Read(initialText, 0, initialText.Length);
// Release all resources
memStream.Close();
cryptoStream.Close();
rdTransform.Dispose();
rijndael.Clear();
// Convert byte[] to string
string decryptedStr = Encoding.ASCII.GetString(initialText);
return (decryptedStr);
}
}
I can't speak regarding the Objective C implementation of Rijndael cipher, but I have used this(C#) code for the basis of some production work and it has worked wonderfully.
Your question is very vague, but in short; yes, it is possible. You will need to figure out what the expectations of your cryptography are (high security or high speed?) and then weigh the benefits of various algorthms and their implementation difficulties in Objective-C and C#.
I don't know Objective C, but for the C# decryption, look into the various CryptoServiceProviders in System.Security.Cryptography.
Here is one example I wrote using TripleDES:
public class TripleDES
{
private byte[] mbKey;
private byte[] mbIV;
private TripleDESCryptoServiceProvider tdProvider = new TripleDESCryptoServiceProvider();
private UTF8Encoding UTEncode = new UTF8Encoding();
// Key: **YOUR KEY**
// Project IV: **YOUR IV**
public TripleDES(string strKey, string strIV)
{
mbKey = UTEncode.GetBytes(strKey);
mbIV = UTEncode.GetBytes(strIV);
}
public TripleDES()
{
//
// TODO: Add constructor logic here
//
}
public string EncryptToString(string strInput)
{
return Convert.ToBase64String(this.EncryptToBytes(strInput));
}
public byte[] EncryptToBytes(string strInput)
{
byte[] bInput = UTEncode.GetBytes(strInput);
byte[] bOutput = ProcessInput(bInput, tdProvider.CreateEncryptor(mbKey, mbIV));
return bOutput;
}
public string DecryptToString(string strInput)
{
return UTEncode.GetString(DecryptToBytes(strInput));
}
public byte[] DecryptToBytes(string strInput)
{
byte[] bInput = Convert.FromBase64String(strInput);
byte[] bOutput = ProcessInput(bInput, tdProvider.CreateDecryptor(mbKey, mbIV));
return bOutput;
}
private byte[] ProcessInput(byte[] input, ICryptoTransform ctProcessor)
{
MemoryStream memStream = new MemoryStream();
CryptoStream crpStream = new CryptoStream(memStream, ctProcessor, CryptoStreamMode.Write);
crpStream.Write(input, 0, input.Length);
crpStream.FlushFinalBlock();
memStream.Position = 0;
byte[] output;
output = new byte[memStream.Length];
memStream.Read(output, 0, output.Length);
memStream.Close();
crpStream.Close();
return output;
}
}
}