I'm using the RSACryptoServiceProvider to encrypt and decrypt simple strings and while it works with normal certificates, it's giving me some grief when it comes to smart cards.
Here is the code I'm using:
private X509Certificate2 _cert // this certificate is set early on in the program
private string Encrypt(string Data)
{
if (string.IsNullOrEmpty(Data)) return default(string);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)_cert.PublicKey.Key;
return Convert.ToBase64String(((rsa.Encrypt(Encoding.Unicode.GetBytes(Data), true))));
}
private string Decrypt(string CipherText)
{
if (string.IsNullOrEmpty(CipherText)) return default(string);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)_cert.PrivateKey;
return Encoding.Unicode.GetString(((rsa.Decrypt(Convert.FromBase64String(CipherText), true))));
}
It does decrypt successfully (no errors) but the encoding isn't correct. It's giving me results like
\u08d8黔㡉Ẑ༴쨳층器\u0888諬翉烽偪䚘螷퓰薑낯ꄯ鯪ꘇ台ᾨ鳞텟칆蘟マ⺁ൿ䤳譻宐Ṹ鉱㒎艴偃堎え뢈癘蚰૩�⸮賆슉ଞ맿댿䀵㓹摵�뼚⡨ቾ᳓낣쏀ꖌ엷ὦ楐豎⸌ꅑ뙳餱Ч鎋筧粅嚄罜칮嬒쐞ڮ묭泊䘐쫦⊗邀☇仇挃箍絁绺罽华⏓፦귪ﻳ咷믭鹺簽艉闼敹Ԓ嵯젨泪ꔤ狫ꆙ\uab41軧\n"
What's also interesting is no matter what I encrypt, the decrypted byte[] length is always 256.
I know smart card private key operations always take place on the card itself so I'm sure that has something to do with it but I was hoping some of you have experience with this and can save me the mounds of trial-and-error.
Thanks!
It seems your Smart Card performs so called raw or textbook RSA. In other words, it only performs modular exponentiation, leaving the PKCS#1 v1.5 (EME-PKCS1-v1_5) or - in your case - OAEP (EME-OAEP decoding) decoding up to you. This padding has the same size as the key size / modulus size. In your case that would be 256 bytes or 2048 bits.
So something is very wrong with the Smart Card that's used. Unpadding should be an integral part of the functionality provided by it; it makes little sense to do that on the PC.
The padding largely consists of random (looking) data so it's little wonder that it looks like random text, especially now UTF-16 LE is being used (incorrectly called Unicode by .NET).
Related
I'm implementing a short RSA program and have this code:
private string Encrypt(string data)
{
BigInteger dataAsBigInteger = new BigInteger(Encoding.UTF8.GetBytes(data));
BigInteger remainder = BigInteger.ModPow(dataAsBigInteger, exponentE, CalculatePublicKey());
return Convert.ToBase64String(remainder.ToByteArray());
}
private string Decrypt(string data)
{
BigInteger dataAsBigInteger = new BigInteger(Convert.FromBase64String(data));
BigInteger remainder = BigInteger.ModPow(dataAsBigInteger, CalculatePrivateKey(), CalculatePublicKey());
return Encoding.UTF8.GetString(remainder.ToByteArray());
}
Unfortunately, I seem to be getting weird ASCII values for the result. I tried with just using numbers instead of text and Decrypt(Encrypt(number)) == number so I know the algorithm is fine so I think it is messing up because of converting to and from byte arrays and performing operations on them.
If this didn't work I was thinking of a better idea for a formula of converting letters to numbers. I can't do A = 1, B = 2, etc. because 11 would be ambiguous with K (11th letter). Maybe if each letter's position (A = 1, B = 2, etc.) was first multiplied by 10 and then you would know the next letter began at a non-zero value?
Is something like this advisable or can the byte arrays be salvaged?
In principle your scheme should work, as long as the resulting BigInteger is not negative or larger than the modulus.
If a cryptographically secure RSA implementation such as OAEP is used then you also need to subtract the overhead of the padding. Usually though you should only encrypt a symmetric key and use hybrid cryptography to allow for almost arbitrary message sizes.
The thing you are trying to do does not make sense. RSA can only encrypt fixed-length messages, integers of the same order-of-magnitude as the public modulus n. (Specifically, if the plaintext m, taken as a number, is small enough that me < n, then the encryption is trivially reversible, and if it is larger than n, it can't be encrypted at all.)
Moreover, you appear to be attempting to implement "textbook RSA", which is insecure. You need to redesign your application so that, instead, it uses RSA as part of a key encapsulation scheme, which securely delivers a symmetric (e.g. AES) key which is used, in an authenticated operation mode, to encrypt the actual message.
This correction to your design will also render your encoding problem moot, since the message proper is now being encrypted using a symmetric cipher that operates on bit streams rather than numbers.
I would be very surprised if C# does not have libraries that do this for you.
I need to derive a key from a salted password using PBKDF2 encryption in a C# & C++ Metro (WinRT) application. What should I use to derive a key using PBKDF2 (like OpenSSL's PKCS5_PBKDF2_HMAC_SHA1 call does) on Metro? Is there a version of OpenSSL that builds on WinRT? (I've read that it only builds on Windows for the desktop platform.) Or is there some other solution I should use?
BTW I could call the function from either C# or C++, so either is fine. Any advice would be much appreciated!
EDIT:
I just found a .NET function named "Rfc2898DeriveBytes" -- details here. If I'm reading that correctly it will do the same thing as OpenSSL's PKCS5_PBKDF2_HMAC_SHA1 call -- is that correct?
EDIT #2:
Unfortunately it looks like I can't use Rfc2898DeriveBytes after all in my Windows 8.1 Metro app because despite what the Microsoft documentation for Rfc2898DeriveBytes says, that API method does not exist in the 'Windows.Security.Cryptography' namespace when building a Windows 8.1 app. Is there anything else I can use?
After much digging around I finally found this link. Here is what I ended up doing in my Metro app:
private static bool GetPBKDFDerivedKey(string password,
byte[] salt, // length = 32 bytes (256 bits)
out byte[] encryptionKeyOut) // length = 32 bytes (256 bits)
{
IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(salt);
KeyDerivationParameters kdfParameters = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000); // 10000 iterations
// Get a KDF provider for PBKDF2 and hash the source password to a Cryptographic Key using the SHA256 algorithm.
// The generated key for the SHA256 algorithm is 256 bits (32 bytes) in length.
KeyDerivationAlgorithmProvider kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256);
IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
CryptographicKey passwordSourceKey = kdf.CreateKey(passwordBuffer);
// Generate key material from the source password, salt, and iteration count
const int keySize = 256 / 8; // 256 bits = 32 bytes
IBuffer key = CryptographicEngine.DeriveKeyMaterial(passwordSourceKey, kdfParameters, keySize);
// send the generated key back to the caller
CryptographicBuffer.CopyToByteArray(key, out encryptionKeyOut);
return true; // success
}
You can use Rfc2898DeriveBytes as the RFC actually defines PBKDF2. Note that you need to make sure you use the same character encoding, salt size and number of rounds to be compatible. Normally SHA1 is used as underlying hash function (which is fine) but beware that PBKDF2 may also use other hash functions. Rfc2898DeriveBytes utilizes SHA1 for the HMAC functionality.
Note that Rfc2898DeriveBytes utilizes UTF-8; this is not documented (even after multiple requests) by Mickeysoft. You can use byte arrays instead if you are unsure about the encoding on both platforms. You should especially be aware of this if you allow characters out of the US ASCII range.
In my scenario, I would like to encrypt a very big number (10^27) using a private key and later be able to decrypt it using a public key. The problem I have is that I want to keep the size of the encrypted text as small as possible.
I know that .NET has support for public key encryption (RSACryptoServiceProvider), but the encrypted text gets so huge.
Would it work to instead treat the private key as a public key?
Would Elliptic curve cryptography produce a smaller output?
First of all, if you want to achieve confidentiality you should always encrypt with the public key, not the private key. RSA encryption is not defined for encryption with the private key, and the results may vary (especially the kind of padding that is applied).
For direct RSA encryption, the size of the encrypted message is identical to the modulus. Now the modulus should be at least 2048 bits by now, and your message is only about (27/3)*10=90 bits. So RSA would have a large overhead, independent on the key used. Using ECIES is therefore likely to give significant benefits.
There are many topics on RSA Encryption and Decryption using BouncyCastle, however I'm encountering some unexpected behaviour.
I'm attempting to encrypt a 64 byte data blocking using a private key of size 64 bytes
I compute the RSA Encryption as followings:
public byte[] Encrypt(byte[] data, AsymmetricKeyParameter key)
{
var engine = new RsaEngine();
engine.Init(true, key);
var blockSize = engine.GetInputBlockSize();
return engine.ProcessBlock(data, 0, blockSize );
}
I compute the decryption using a public key as follows
public byte[] Decrypt(byte[] data, AsymmetricKeyParameter key)
{
var engine = new RsaEngine();
engine.Init(false, key);
var blockSize = engine.GetInputBlockSize();
return engine.ProcessBlock(data, 0, blockSize );
}
What I'm finding is that when I encrypt my 64 data using a 64 byte Private Key I get back a 64 byte encrypted dataBlock.
However when I decode the 64 byte array using a 64 byte public key I get back a data block of size 62 bytes. What is stranger is that the values contained in the 62 byte array equal the values of the 64 byte original array (pre encryption) however the decoded array is missing the first index of the original data and the final index.
I've tried using different keys and different sets of data and the same thing happens.
I must be doing something wrong, but I can't see it.
Cheers.
You got the essential concepts wrong.
512 bit RSA is very weak, use at least 1024 bits
A private key is not for encryption. It's for decryption and signing. The public key is for encryption and verification.
Padding is essential for RSA security. A typical padding scheme requires several dozen bytes.
Even with textbook RSA, RSA can only work on values smaller than the modulus. So a 512 bit modulus can't operate on arbitrary 64 byte / 512 bit values. But only on 511 bits.
You should take a step back, and describe what you actually want to achieve, so we can find a scheme that fits your needs. Only after that you should worry about implementing it.
I want to use encryption algorithm available in .Net Security namespace, however I am trying to understand how to generate the key, for example AES algorithm needs 256 bits, that 16 bytes key, and some initialization vector, which is also few bytes.
Can I use any combination of values in my Key and IV? e.g. all zeros in Key and IV are valid or not? I know the detail of algorithm which does lots of xors, so zero wont serve any good, but are there any restrictions by these algorithms?
Or Do I have to generate the key using some program and save it permanently somewhere?
I want to store data in database after encryption, the secure profile data like username, password, phone number etc, and the key will be available to database user mentioned in connection string only, and to the administrator.
You really ought to do this the correct way :)
1) Use a securely generated random IV
2) Use a securely generated random key
3) Don't use ECB mode - EVER
AesManaged aes = new AesManaged();
aes.GenerateKey();
aes.GenerateIV();
The code above will correctly and securely generate a random IV and random key for you.
Sounds like you need to read into the Rfc2898DeriveBytes class.
Rfc2898DeriveBytes.GetBytes();
It has a method(above) that allows you to tailor the size of byte arrays that are fed into the .Key and .IV properties on a symmetric encryption algorithm, simply by feeding an int value. The MS official 70-536 book suggests doing this pro-grammatically by dividing the KeySize property / 8.
I.e TripleDes or AESManaged. Whatever you use, the algorithm itself will have some pre-reqs that will need meeting first. I.e satisfying the key size conditions. The RunTime will automatically fill the properties and fields and etc the best and most strongest values for you. But the IV and Key needs to come from you. This how you can do the following:
RijndaelManaged myAlg = new RiRijndaelManaged();
byte[] salt = Encoding.ASCII.GetBytes("Some salt value");
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes("some password", salt);
myAlg.Key = key.GetBytes( myAlg.KeySize / 8);
myAlg.IV = key.GetBytes( myAlg.BlockSize / 8);
// myAld should now fully set-up.
Above you can see what I mean by doing it pro-grammatically, as it should pretty much
do it all for you, without you even really having to bat an eye-lid as to meeting it's pre-reqs.
The Microsoft 70-536 book states that the .Key properties expect the byte arrays you supply
to them in bytes and not bits. The RFC class works in bytes where as an algorithms KeySize property works in bits. 1 byte = 8 bits. Can you see where this is going ... ?
This should give you an idea as to why the above sample peice of code is done the way it is! I studied it and it makes pretty darn good sense to me!
The above answer should allow you to create your algorithm object with supplied password and a static salt value that can be hard code at both ends. Only thing you need to do is worry about how you going to make sure that the byte arrays stored at .Key and .IV are safely transported to a recipient so that can successfully decrypt the message you encrypted. By safely reconstructing the same algorithm object.
OBTW:
AESManaged has a keysize req': 128Bits = 16 Bytes !!!
(8*8 = 64, 64Bit / 8bits per Byte = 8 Bytes) Therefore
64*2 = 128Bit, 8*2, ==> 16bytes key size !
256Bit = 32Bytes !!!!
According to the 70-536 official training kit book, Aes is limited to having keysize of 128bits in size. 256bits,192 and 128 key size for example can be used with the Rijndael class.
You could on the other hand completely forget all that crap and simply use .GenerateKey and GenerateIV methods instead to save you all the hassle of sorting out a pre-shared and agreed password and static salt values. Your only concern is figuring out a way of storing and retrieving the key and IV byte arrays. Binary Formatter? .
If you are using encryption to exchange data then you will need a key exchange protocol, but you don't make one yourself instead use one off-the-shelf like TLS or SSL.
If you use encryption to store data then you generate the IV using CryptGenRandom (or its .net equivalent RandomNumberGenerator.GetBytes) and save it along the document (in clear, no need to protect the IV). You never write down the key, the key is provided by the user. Usualy you derive the key from a password phrase using CryptDeriveKey, or its .Net equivalent PasswordDeriveKey.CryptDeriveKey.
Update
To store a secret in the database that is available only to the user and an administrator you need to use 3 keys:
one to encrypt the data with (call it the DK key)
one user key to encrypt the DK key (call it UK)
one administrator key to encrypt the DK key (call it AK)
In theory you encrypt the data with DK and then encrypt the DK with UK and save it, and encrypt the DK with AK and save it. This way the user can use again the UK to decrypt the DK and then decrypt the data, and the administrator can use the AK to decrypt the DK and then decrypt the data. The big problem is the fact that the system is always automated, so the system needs access to the administrator's key which means is not truly a persnal key of the administrator, but instead is a system key (it cannot be used for purposes of non-repudiation for instance).
As a heads up, knowledge of what IV is or how to use AES from C# and how cryptography algorithm work will get you exactly 0 (zero) traction in solving this kind of problems. The issue is never what IV and key to use, the issue is always key provisioning. For actual crypto operations, just use the built-in support from the database, see Cryptography in SQL Server. I can easily argue that the only facility you need is TDE (Transparent Data Encryption) to protect against accidental loss of media.
Generate a random letters / hex code in a specific length.
This function (taken from here) return a random key in a specific length:
private static string CreateSalt(int size)
{
//Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
// Return a Base64 string representation of the random number.
return Convert.ToBase64String(buff);
}
Use System.Security.Cryptography.RandomNumberGenerator to generate random bytes:
var rnd = new System.Security.Cryptography.RandomNumberGenerator.Create();
var key = new byte[50];
rnd.GetBytes(key);
It really depends on what you ned to do with the key.
If the key is to be generated by the computer (and can be any random value) I generally take a SHA256 of a couple GUIDs. This is about as random as you're going to get without a hardware random number generator.
You can use keys with all 0s but obviously it won't be very secure.