WHAT'S NEW?
Loading...
Showing posts with label Encryption. Show all posts
Showing posts with label Encryption. Show all posts

Index

  • Prerequisites
  • Source Material
  • CA Creation
  • Service Certificate Creation
  • Certificate Permissions
  • Client Certificate deployment
  • Config file examples

Intro

The idea of this post is follow the different steps you need to accomplish in order to build and use a ssl certificate on your own.

Prerequisites

VS 2013 cmd prompt
FindPrivateKey (http://blog.rhysgoodwin.com/windows-admin/findprivatekey-exe-pre-compiled/)

Source Material

Create Development Certificate Authority and Certificate (https://msdn.microsoft.com/en-gb/library/ff647171.aspx)
How to: Use Certificate Authentication and Message Security in WCF Calling from Windows Forms (https://msdn.microsoft.com/en-us/library/ff648360.aspx)

CA Creation

  • makecert -n "CN=RootCATestMWM" -r -sv RootCATestMWM.pvk RootCATestMWM.cer
  • Install RootCATestMWM.cer into Computer Certificates under Trusted Root Certification Authorities
  • makecert -crl -n "CN=RootCATestMWM" -r -sv RootCATestMWM.pvk RootCATestMWM.crl
  • Install RootCATestMWM.crl into Computer Certificates under Trusted Root Certification Authorities

Service Certificate Creation

makecert -sk MWMWCFkey -iv RootCATestMWM.pvk -n "CN=MWMWCF" -ic RootCATestMWM.cer -sr localmachine -ss my -sky exchange -pe

Certificate Permissions

  • FindPrivateKey.exe My localmachine -n "CN=MWMWCF"
  • view permissions (swap out private key and folder as necessary)
  • cacls C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\9a4xx8832dca5a244d3f9_a8ab4228-7aa5-413e-xxxx-1a5f48e30d15
  • edit permissions (swap out private key and folder as necessary)
  • cacls C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\9ax5fe8832dca5a244d3f9_a8ab4228-7aa5-413e-be66-1a5f48e30d15 /E /G "NT AUTHORITY\NETWORK SERVICE":R

Client Certificate deployment

Copy the root CA certificate (RootCATest.cer) and private key file (RootCATest.pvk), to the client machine.
makecert -sk MWMWCFKey -iv RootCATestMWM.pvk -n "CN=MWMWCFClient" -ic RootCATestMWM.cer -sr CurrentUser -ss my -sky signature -pe MWMWCFClient.cer

makecert -sk MWMWCFKey -iv RootCATestMWM.pvk -n "CN=MWMWCF" -ic RootCATestMWM.cer -sr LocalMachine -ss my -sky signature -pe MWMWCFClient.cer


WCF URL ACL Grant Permissions

netsh http add urlacl url=http://+:PortNumber/MyService user="NT AUTHORITY\NETWORK SERVICE"

Config file examples

WCF Service config Example



WCF Client Config Example


That's all for today, I hope this posts gives you clarity on how to create your own Certificates and start securing up your applications.

Index


  • Introduction
  • Working with encryption
  • Hashing
  • Certificates
  • Code access permissions
  • Secure string data
  • References

Introduction

This post is part of a series of post to help you prepare the MCSD certification, particularly the certification exam 70-483, based on the book:


You will find all the code available in the following GitHub repository. Lets talk a little bit about threads and how they work using a .Net development environment.

Working with encryption


Major encryption techniques:

  • Symmetric or secret key
    • Unique shared key between sender and recipient
    • AES: Advanced Encryption Standard
    • .Net System.Security.Cryptography class
    • It works on byte sequences by using a key and IV (Initialization vector: randomness)
  • Asymmetric or public key
    • prevents someone getting the secret key during the exchange process in Symmectric enc.
    • Sender a recipient create both private/public keys.
    • Encrypt messages with your recipient's public key which will only be decrypted with recipient's private key.
    • .Net RSACryptoServiceProvider and DSACryptoServiceProvider classes.
    • Keep your private key safe with .Net container using CspParameters

C# AES coding example: notice how the SymmetrciAlgorithm class allows you to build both encryptor and decryptor.



C# RSA coding example


C# asymmetric key container example



Hashing


Hashing simplifies the process of compare elements. Imagine a list where you are adding only unique elements. You have to compare each new candidate with every element on the list. This ends taking down performance. Hashing can help you out generating unique identifiers from you list of elements so you don't have to compare the whole entity each time a new candidate appears, you just need to compare the unique hash code, simplifying the logic operations.

You can use hash to distribute the elements of a list in shorter lists that we can call "buckets". The hashing process of your elements will be used to return the bucket where the element needs to be stored. Conclusions:
  • Equal items should have equal hash codes.
  • Your implementation of GetHashCode() should return always the same, so it shouldn't be  based on dates or times.
  • Can be used to check the integrity of a message
  • Use the SHA256Managed algorithm provided in .Net SHA256 class to generate / compare your codes.

Certificates

Certificates are built on top of Asymmetric encryption and Hashing. If Bob wants to send a message to Mike, he will hash his message and then encrypt both message and hash using Mike's public key. Then, Mike will decrypt both items using his private key and will validate the integrity of the message comparing the hash received and a new hash based on Bob decrypted message. Certificate glossary:

  • Public Key Infrastructure (PKI): authenticate and verify the validity of each involved party
  • Certificate Authority (CA): third-party issuer of certificates trust-worthly by all parties
  • Used to secure Internet communications. 
  • HTTPS: communication protocol ensures that a client is talking with the right server, not to an impostor.
.Net provides a tool to generate your own X.509 test certificates called: makecert.exe. With the following console commands you'll end up creating your own new certificate and installing it on your machine:

makecert testCert.cer
makecert -n "CN=WouterDeKort" -sr currentuser -ss testCertStore

Code access permissions


.Net helps you protect your computer from malicious code via the "Code Access Security" (CAS). Instead of giving all every application full trust, apps can be restricted on the types of resources they can access. The Common Language Runtime (CLR) ensures your code has the correct permissions to access privileged resources. Each code access permissions represents:
  • right to access a resources (file)
  • right to perform  a protected operation (accessing unmanaged code)
Can be used in case you want to allow plugins connect to your app. Then CAS:
  • defines permissions for accessing system resources.
  • enables code to demand that its callers have specific permissions.
  • each callers possess a digital signature
  • enforces all those at runtime
It works in two ways:
  • declarative: by decorating your methods with permissions required
  • imperative: requesting those rights directly from your code (ie: FileIOPermission)

Secure string data


Working with strings in your code is not secure because:

  • The GC can move the variables in memory and leave copies around
  • It's not encrypted
  • Is immutable (with every change a new copy is generated)
  • No way for the GC to remove all copies from memory
To secure your strings you can use the .Net System.Security.SecureString:
  • Automatically encrypts its content
  • Pinned to a memory location
  • It's mutable
  • The GC doesn't move it.
  • Implements IDisposable interface
The only problem comes when it's initialized and you want to pass the content in. That's why the only way to populate it is going one character at a time. See the following example:


Index


  • Intro
  • Encryption techniques
  • Hashing
  • Symmetric and asymmetric encryption
  • References

Intro

Welcome back! Today is all about how to encrypt your data, different types of encryption, hashing messages and symmetric encryption



Encryption techniques

An encryption algorithm makes data unreadable to any person or system until the associated decryption algorithm is applied. It does not hide data; it makes it unreadable. People use to confuse encryption with compression and they are not the same.

Types:

  • File encryption: this is the most basic encryption pattern for .net developers. It's very useful because you will end encrypting your files and any windows user won't be able to read the content of your encrypted messages. This method uses Windows data protection mechanism behind the scenes but this is a kind of short cut. Ex:
  • const string dataToProtect = "This is a bunch of super secret content!";
    var dataToProtectAsArray = Encoding.Unicode.GetBytes(dataToProtect);
    
    var fileName = Path.Combine(Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments),
        "MyDataFile.txt");
    
    // Encrypt a file in the file system
    File.WriteAllText(fileName, dataToProtect);
    
    // now we can encrypt it - only we can access it now
    File.Encrypt(fileName);
    
  • Windows data protection: this allows you to protect data in memory you might want to save into a database or provide via some web service. In the following example I'm encrypting some data defining a particular scope, which will be used to decrypt it, so it's an extra level of security. Ex:
  • // Windows Data Protection (we can also protect for the LocalMachine too)
    // note, the null can be replaced with a byte[] for additional entropy
    var wdpEncryptedData = ProtectedData.Protect(
        dataToProtect, null, DataProtectionScope.CurrentUser);
    
    var wdpUnEncryptedData = ProtectedData.Unprotect(
        wdpEncryptedData, null, DataProtectionScope.CurrentUser);
    var wdpUnencryptedString = Encoding.Unicode.GetString(
        wdpUnEncryptedData);
    
    Debug.Assert(dataToProtect.Equals(wdpUnencryptedString));
    
  • Hashing: the main usage is signing data, which you could think like a wax sealed in an envelope which proves it hasn't been opened since the last time that whoever signed it.
  • Symmetric and asymmetric: this encryption technique is focused in sharing data beyond your user's space.

Think about encryption as a process you ran over the message you want to hide. It's a intensive process and the more intensive the more secure but more resources/time you'll need to perform the conversion of your message.

Hashing

Mainly used for signing and validation. A hash is a value which always is generated in the same way for the data that needs to be encrypted. Is a one-way encryption algorithm, which basically means you can't revert the transformation applied (except, maybe, by brute-force attack). It's fast depending on the algorithm. It's also useful to storing information in a shorter way. For example, you might want to store a hashed password in a database.

There are different approaches to create this codes like:
  • MD5: 16 characters which could produce collisions (same hash from different messages) because of the small amount of characters.
  • SHA (SHA1, SHA256, SHA384, SHA512): 256 is the most common. Both 384 and 512 take the same amount of time to execute, so go for the 512 in order to get more security.
The longer the hash you want to create the smaller the chances to get any collisions. In the following example, I'll show you how to encrypt a message using SHA256:

// hashing - one-way encryption

// this represents a hashed password stored in a database
var storedPasswordHash = new byte[]
{
    148, 152, 235, /* ... more characters ... */
};

var password = Encoding.Unicode.GetBytes("P4ssw0rd!");
var passwordHash = SHA256.Create().ComputeHash(password);

// nice convenience method - can also supply a custom comparator
if (passwordHash.SequenceEqual(storedPasswordHash))
{
    Console.WriteLine("Password match!");
}

As you can see in the previous example, first we are performing a conversion of our password into an array of bytes. That will be the content we'll provide into the SHA256 algorithm instance. Finally we compare the result of the encryption saved in "passwordHash" with the already storedPasswordHash variable which contains the value from the database. If everything matches we'll get the "Password match!" message printed in the console.

Symmetric and asymmetric encryption

For this particular encryption approach, we need to use a key in order to perform our encryption. For the symmetric type we use just one key, and for the asymmetric two. First type is faster. There are five algorithms in the .Net framework:

  • AES (recommended)
  • DES
  • RC2
  • Rijndael
  • TripleDES


Asymmetric aka "Public key" encryption uses two keys as you know. One is used for encryption and the other for decryption. Commonly used for digital signatures and typical .Net frameworks are:

  • DSA
  • ECDiffielHellman
  • ECDsa
  • RSA (recommended)


References