Upload
manu-cohen-yashar
View
386
Download
1
Tags:
Embed Size (px)
DESCRIPTION
Cryptography in .Net
Citation preview
SELA DEVELOPER PRACTICEMay 5-9, 2013
Manu Cohen-Yashar
Cryptography in C#
Why
Hash
Hash
• The problem: Create a number that will represent the information
• Hash – Mathematical operation that maps the infinity to a group of numbers
• We can say that a hash takes an arbitrary block of data and returns a fixed-size bit string
• Every hash value can be created by infinite inputs
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel4
Why do we need the hash
• If we take two values and both of them result the same Hash it is a very good chance that the values are equal
• To prove a knowledge of a secret• Don’t tell me your secret; just prove to me that you
know it…
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel5
Good Hash
• If the input change it is most certain that the hash will change (There is never 100%)
• Hash values are random
• It is impossible to go back from the hash value to the original data
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel6
Hash Algorithms
• There are many hash algorithms• MD5
• SHA-1
• SHA-256
• More
• It is possible to brute force a hash• Simple look for two values that give the same result
• Those values are then written in huge databases for future use
• Your responsibility is to choose a good algorithm
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel7
Hash in Code
private byte[] ComputeHash(byte[] msg)
{
return new SHA1CryptoServiceProvider().ComputeHash(msg);
}
Digital Signature
Digital Signature
• The problem: To insure the integrity of information
• Integrity is : Source and Content
• How:1. Take the information and hash it
2. Encrypt the hash result with your private key
• This is a digital signature
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel10
Digital Signature
Create:
1. Create a hash
2. Encrypt the hash using the message originator Private key
Verify:
1. Decrypt the Digital signature using the originator Public key
2. Compute the message hash and compare with the decrypted digital signature
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel11
Sign in Code
public byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert)
{
ContentInfo contentInfo = new ContentInfo(msg);
SignedCms signedCms = new SignedCms(contentInfo);
CmsSigner cmsSigner = new CmsSigner(signerCert);
signedCms.ComputeSignature(cmsSigner);
return signedCms.Encode();
}
Verify in Code
static public bool VerifyMsg(byte[] encodedSignedCms){
bool result = true;SignedCms signedCms = new SignedCms();signedCms.Decode(encodedSignedCms); try{
signedCms.CheckSignature(true); }catch (CryptographicException e){
result = false;}return result;
}
Symmetric Encryption
Conventional Cryptography
• To encrypt data we uses symmetrical algorithms• same key material used to encrypt and decrypt
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel15
Symmetric Encryption Types
• There are two groups of algorithms• Stream ciphers
• Fast but key can be used only once
• Block ciphers• Slower than stream but key can be used more than once
• Provided by System.Security.Cryptography
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel16
Block Ciphers
• How a block cipher works• Input is broken up
into fixed size blocks
(typically 8 or 16 bytes)
• Transformation f() applied
to key, result xor’d
into block
• This is known as a
“round” – 16 to 32
rounds is typical
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel17
f()
f() xor Round 1
Round N
key plaintext block
xor
ciphertext block
Block Ciphers (Symmetric)
• Block Cipher is a symmetric Key cipher which operates on a fixed-length groups of bits, termed blocks
• Input and output are the same size
• The exact transformation is controlled using the Key
• Algorithms: DES, 3DES
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel18
Block Ciphers
• If we only break the info into blocks and decrypt them, identical blocks would result identical ciphers, thus, in some senses it doesn't provide message confidentiality at all
• Cipher-Block Chaining (CBC)• Each block of plaintext is XORed with the previous ciphertext block before
being encrypted. This way, each ciphertext block is dependent on all plaintext blocks up to that point
• CBC is the most commonly used mode of operation. Its main drawback is that, it is sequential, and cannot be parallelized
• Initialization vector (IV)• IV - a sort of dummy block to kick off the process for the first real
block, and also provide some randomization for the process. There is no need for the IV to be secret, but it is important that it is never reused with the same key
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel19
Cipher-Block Chaining (CBC)
20© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel
Encrypting data in .NET
• Setting up• Choose an algorithm and implementation parameters
• Generate an initialization vector (IV)
• Choose a key
• Encrypting• Record the initialization vector for use, during
decryption
• Create a Crypto Stream object based on your key
• Pump data through the stream to encrypt it
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel21
Algorithms and Implementations in .Net
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel22
SymmetricAlgorithm
DES
RC2
TripleDES
DESCryptoServiceProvider
RC2CryptoServiceProvider
RijndaelManaged
TripleDESCryptoServiceProvider
Rijndael
Encrypt in Code
public static Stream EncryptDataToStream(Stream instream, byte[] key, byte[] initVector){
TripleDES encAlg = TripleDES.Create();
encAlg.Key = key;encAlg.IV = initVector;MemoryStream memStream = new MemoryStream();
CryptoStream encryptorStream = new CryptoStream(memStream, encAlg.CreateEncryptor(), CryptoStreamMode.Write);
const int bufferLen = 4096;byte[] buffer = new byte[bufferLen];int count = 0;int bytecount = 0;while ((count = instream.Read(buffer, 0, bufferLen)) > 0){
encryptorStream.Write(buffer, 0, count);bytecount += count;
}instream.Close();return memStream;
}
Decrypting data in .NET
• Setting up• Choose the same algorithm you used to encrypt
• Retrieve the initialization vector (IV) used during encryption
• Retrieve the key
• Decrypting• Create a CryptoStream object based on your key
• Pump data through the stream to decrypt it
• Close the CryptoStream immediately when done decrypting
• This causes it to eat any leftover padding from the input stream
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel24
Decrypt in Code
public static byte[] DecryptData(byte[] Cipher, byte[] key, byte[] initVector)
{TripleDES encAlg = TripleDES.Create();encAlg.Key = key;encAlg.IV = initVector;MemoryStream Dec_MeM_Stream = new MemoryStream();CryptoStream DecryptorStream = new CryptoStream(Dec_MeM_Stream,
encAlg.CreateDecryptor(), CryptoStreamMode.Write);
DecryptorStream.Write(Cipher, 0, Cipher.Length);DecryptorStream.FlushFinalBlock();DecryptorStream.Close();
byte[] decryptedData = Dec_MeM_Stream.ToArray();return decryptedData;
}
Choosing an algorithm
• Narrow down your choices• 1) Use well-known algorithms. Avoid obscure ones
• 2) Use an algorithm that supports your required key length
• 3) Prefer a block cipher to a stream cipher
• 4) Pick an algorithm that performs well on your platform
• Some algorithms perform better in hardware (DES)
• Some perform well in software (RC2, IDEA)
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel26
Key Management
Key Protection
• Why encrypt if the key is not protected?
What is DPAPI
• Data Protection API is a Windows infrastructure that was created to protect secrets
• DPAPI consists of two functions, CryptProtectData and CryptUnprotectData
• The protection is done per user or per machine
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel29
DPAPI
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel30
DPAPI – Key Creation
1. Generates a strong key called a MasterKey
2. PKCS#5 create a key from the user password to protect the master key (Triple-DES)
3. A symmetric session key is generated based on the MasterKey, some random data, and any optionaladditional entropy
4. Using the Session key the DATAis encrypted
5. The master key and the user passwordare kept in the user's profile directory, protected by the user's current password
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel31
System.Security.ProtectedData
• Simple wrapper to the DPAPI infra with two main functions:• Protect and Unprotect
• DataProtectionScope• CurrentUser - encrypts the data so that only the
currently logged on user can decrypt it
• LocalMachine – encrypt the data so that any process running on the current machine can decrypt it. (useful in a server scenario)
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel32
DPAPI Code
Byte[] cipher = ProtectedData.Protect(dataToEncrypt, entropy,DataProtectionScope.LocalMachine)
Byte[] data = ProtectedData.Unprotect (cipher,entropy,DataProtectionScope.LocalMachine
Secure String
• SecureString stores its data using the Data Protection API
• Data inside SecureString is always in its encrypted form
• SecureString isn’t just a simple wrapper around System.string
• To be effective:Secret must never ever find its way into a normal managed string !
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel34
Asymmetric Cryptograp
hy
Asymmetric cryptography
• Not for hiding large sets of data !!!
• Slow
• Based on key pair
• Used to exchange keys and digital signatures
RSA
• In 1977, RSA was born by• Ron Rivest
• Adi Shamir
• Leonard Adleman
• RSA is the root of modern digital signature
• RSA is the root for SSL
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel37
Public and Private Keys
• Keys are generated in pairs• Public key
• Private key
• Public key is a large number
• Private key is its Prime factors
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel38
X.509 Certificates
• Placeholder for public keys
• Contain metadata about the key
• Issued (signed) by a trusted certificate authority
Find Certificate
private static X509Certificate2 FindCertificate(string certificateName, StoreName storeName, StoreLocation storeLocation)
{X509Store store = new X509Store(storeName, storeLocation);X509Certificate2 certificate = null;try{
store.Open(OpenFlags.MaxAllowed);X509Certificate2Collection collection = store.Certificates.Find(
X509FindType.FindBySubjectName, certificateName, false); if (collection.Count > 0)
certificate = collection[0];else
throw new Exception(string.Format("CertificateNotFound {0}", certificateName));
}finally{ store.Close(); }return certificate;
}
Encrypy Key
public static byte[] EncrypyKey(byte[] key, StoreName storeName, StoreLocation storeLocation, string certificateName)
{ // Find the client certificateX509Certificate2 certificate = FindCertificate(certificateName,
storeName, storeLocation);RSACryptoServiceProvider rsa = certificate.PublicKey.Key as
RSACryptoServiceProvider;
return rsa.Encrypt(key, true);}
Decrypt Key
public static byte[] DecrypyKey(byte[] cipher, StoreName storeName,StoreLocation storeLocation, string certificateName)
{
// Find the client certificate
X509Certificate2 certificate = FindCertificate(certificateName, storeName,
storeLocation);
RSACryptoServiceProvider rsa = certificate.PrivateKey as
RSACryptoServiceProvider;
return rsa.Decrypt(cipher, true);}
Summary
• Hash
• Digital Signature
• Symmetric Encryption
• Key management
• Certificates
• Asymmetric Encryption
Thank You