SELA DEVELOPER PRACTICE
May 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
infi...
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 va...
Good Hash
• If the input change it is most certain that the hash
will change (There is never 100%)
• Hash values are rando...
Hash Algorithms
• There are many hash algorithms
• MD5
• SHA-1
• SHA-256
• More
• It is possible to brute force a hash
• S...
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...
Digital Signature
Create:
1. Create a hash
2. Encrypt the hash using the message originator
Private key
Verify:
1. Decrypt...
Sign in Code
public byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert)
{
ContentInfo contentInfo = new ContentInfo(ms...
Verify in Code
static public bool VerifyMsg(byte[] encodedSignedCms)
{
bool result = true;
SignedCms signedCms = new Signe...
Symmetric
Encryption
Conventional Cryptography
• To encrypt data we uses symmetrical algorithms
• same key material used to encrypt and decrypt...
Symmetric Encryption Types
• There are two groups of algorithms
• Stream ciphers
• Fast but key can be used only once
• Bl...
Block Ciphers
• How a block cipher works
• Input is broken up
into fixed size blocks
(typically 8 or 16 bytes)
• Transform...
Block Ciphers (Symmetric)
• Block Cipher is a symmetric Key cipher which operates on a
fixed-length groups of bits, termed...
Block Ciphers
• If we only break the info into blocks and decrypt
them, identical blocks would result identical ciphers, t...
Cipher-Block Chaining (CBC)
20
© Copyright SELA software & Education Labs
Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Isra...
Encrypting data in .NET
• Setting up
• Choose an algorithm and implementation parameters
• Generate an initialization vect...
Algorithms and
Implementations in .Net
© Copyright SELA software & Education Labs
Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51...
Encrypt in Code
public static Stream EncryptDataToStream(Stream instream, byte[] key, byte[]
initVector)
{
TripleDES encAl...
Decrypting data in .NET
• Setting up
• Choose the same algorithm you used to encrypt
• Retrieve the initialization vector ...
Decrypt in Code
public static byte[] DecryptData(byte[] Cipher, byte[] key,
byte[] initVector)
{
TripleDES encAlg = Triple...
Choosing an algorithm
• Narrow down your choices
• 1) Use well-known algorithms. Avoid obscure ones
• 2) Use an algorithm ...
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 tw...
DPAPI
© Copyright SELA software & Education Labs
Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202
Israel
30
DPAPI – Key Creation
1. Generates a strong key
called a MasterKey
2. PKCS#5 create a key from the user
password to protect...
System.Security.ProtectedDat
a
• Simple wrapper to the DPAPI infra with two main
functions:
• Protect and Unprotect
• Data...
DPAPI Code
Byte[] cipher = ProtectedData.Protect
(dataToEncrypt, entropy,DataProtectionSco
pe.LocalMachine)
Byte[] data = ...
Secure String
• SecureString stores its data using the Data
Protection API
• Data inside SecureString is always in its enc...
Asymmetric
Cryptograp
hy
Asymmetric cryptography
• Not for hiding large sets of data !!!
• Slow
• Based on key pair
• Used to exchange keys and dig...
RSA
• In 1977, RSA was born by
• Ron Rivest
• Adi Shamir
• Leonard Adleman
• RSA is the root of modern digital signature
•...
Public and Private Keys
• Keys are generated in pairs
• Public key
• Private key
• Public key is a large number
• Private ...
X.509 Certificates
• Placeholder for public keys
• Contain metadata about the key
• Issued (signed) by a trusted certifica...
Find Certificate
private static X509Certificate2 FindCertificate(string certificateName,
StoreName storeName, StoreLocatio...
Encrypy Key
public static byte[] EncrypyKey(byte[] key, StoreName storeName,
StoreLocation storeLocation, string certifica...
Decrypt Key
public static byte[] DecrypyKey(byte[] cipher, StoreName storeName,
StoreLocation storeLocation, string certif...
Summary
• Hash
• Digital Signature
• Symmetric Encryption
• Key management
• Certificates
• Asymmetric Encryption
Thank You
Upcoming SlideShare
Loading in …5
×

Crypography in c#

933 views

Published on

Cryptography in .Net

Published in: Software, Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
933
On SlideShare
0
From Embeds
0
Number of Embeds
21
Actions
Shares
0
Downloads
18
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • Many security models attach security to users and their groups (or roles). This means that : all code run on behalf of these users, are either permitted or not permitted to perform operations on critical resources.The .NET Framework provides a developer defined security model called role-based security that functions in a similar vein.Role Based Security's principal abstractions are Principals and Identity. Additionally, the .NET Framework also provides security on code and this is referred to as code access security (also referred to as evidence-based security).With code access security, user may be trusted to access a resource but if the code is not trusted, then access to the resource will be denied.
  • Current Security Products such as Antivirus, Firewalls Industry Detection Systems are designed as stand alone pieces of equipment or software.Near-Term Problem: Ensuring Programs are : Memory-Safe, Type-Safe So fine-grained access control can be enforced.Long-Term Problem: Ensuring that Distributed computing system enforce system-wide information security policies:ConfidentialityIntegrityAvailabilityConfidentiality, integrity : end-to-end security described by information-flow policies.
  • Crypography in c#

    1. 1. SELA DEVELOPER PRACTICE May 5-9, 2013 Manu Cohen-Yashar Cryptography in C#
    2. 2. Why
    3. 3. Hash
    4. 4. 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 Israel 4
    5. 5. 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 Israel 5
    6. 6. 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 Israel 6
    7. 7. 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 Israel 7
    8. 8. Hash in Code private byte[] ComputeHash(byte[] msg) { return new SHA1CryptoServiceProvider().ComputeHash(msg); }
    9. 9. Digital Signature
    10. 10. 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 Israel 10
    11. 11. 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 Israel 11
    12. 12. 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(); }
    13. 13. 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; }
    14. 14. Symmetric Encryption
    15. 15. 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 Israel 15
    16. 16. 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 Israel 16
    17. 17. 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 Israel 17 f() f() xor Round 1 Round N key plaintext block xor ciphertext block
    18. 18. 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 Israel 18
    19. 19. 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 Israel 19
    20. 20. Cipher-Block Chaining (CBC) 20 © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel
    21. 21. 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 Israel 21
    22. 22. Algorithms and Implementations in .Net © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 22 SymmetricAlgorithm DES RC2 TripleDES DESCryptoServiceProvider RC2CryptoServiceProvider RijndaelManaged TripleDESCryptoServiceProvider Rijndael
    23. 23. 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; }
    24. 24. 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 Israel 24
    25. 25. 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; }
    26. 26. 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 Israel 26
    27. 27. Key Management
    28. 28. Key Protection • Why encrypt if the key is not protected?
    29. 29. 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 Israel 29
    30. 30. DPAPI © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 30
    31. 31. 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 optional additional entropy 4. Using the Session key the DATA is encrypted 5. The master key and the user password are 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 Israel 31
    32. 32. System.Security.ProtectedDat a • 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 Israel 32
    33. 33. DPAPI Code Byte[] cipher = ProtectedData.Protect (dataToEncrypt, entropy,DataProtectionSco pe.LocalMachine) Byte[] data = ProtectedData.Unprotect (cipher, entropy,DataProtectionScope.LocalMachine
    34. 34. 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 Israel 34
    35. 35. Asymmetric Cryptograp hy
    36. 36. Asymmetric cryptography • Not for hiding large sets of data !!! • Slow • Based on key pair • Used to exchange keys and digital signatures
    37. 37. 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 Israel 37
    38. 38. 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 Israel 38
    39. 39. X.509 Certificates • Placeholder for public keys • Contain metadata about the key • Issued (signed) by a trusted certificate authority
    40. 40. 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; }
    41. 41. Encrypy Key public static byte[] EncrypyKey(byte[] key, StoreName storeName, StoreLocation storeLocation, string certificateName) { // Find the client certificate X509Certificate2 certificate = FindCertificate(certificateName, storeName, storeLocation); RSACryptoServiceProvider rsa = certificate.PublicKey.Key as RSACryptoServiceProvider; return rsa.Encrypt(key, true); }
    42. 42. 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); }
    43. 43. Summary • Hash • Digital Signature • Symmetric Encryption • Key management • Certificates • Asymmetric Encryption
    44. 44. Thank You

    ×