Menu
- Which Cryptographic System Generates Encryption Keys In Windows 7
- Which Cryptographic System Generates Encryption Keys Windows 10
- Cryptographic Key Types
- Cryptographic Key Management Software
This walkthrough demonstrates how to encrypt and decrypt content. The code examples are designed for a Windows Forms application. This application does not demonstrate real world scenarios, such as using smart cards. Instead, it demonstrates the fundamentals of encryption and decryption.
Public Key Cryptography, or Asymmetric Cryptography, is a cryptographic system that uses pairs of keys: Public Key and Private Key. It is one of the most important (if not the most important) part of cryptocurrency protocols, and it is used in sev. ICSF supports two main types of cryptographic processes: Symmetric, or secret key, algorithms, in which the same key value is used in both the encryption and decryption calculations. Asymmetric, or public key, algorithms, in which a different key is used in the decryption calculation than was used in the encryption calculation. Key management is the secure handling and storage of cryptographic keys. This includes key storage and retrieval, key encryption and conversions, and key distribution. Key storage on the system includes the following: Cryptographic Services keystore. In addition, keys can also be stored on the Cryptographic Coprocessors themselves.
This walkthrough uses the following guidelines for encryption:
- Use the RijndaelManaged class, a symmetric algorithm, to encrypt and decrypt data by using its automatically generated Key and IV.
- Use the RSACryptoServiceProvider, an asymmetric algorithm, to encrypt and decrypt the key to the data encrypted by RijndaelManaged. Asymmetric algorithms are best used for smaller amounts of data, such as a key.NoteIf you want to protect data on your computer instead of exchanging encrypted content with other people, consider using the ProtectedData or ProtectedMemory classes.
The following table summarizes the cryptographic tasks in this topic.
Task | Description |
---|---|
Creating a Windows Forms application | Lists the controls that are required to run the application. |
Declaring global objects | Declares string path variables, the CspParameters, and the RSACryptoServiceProvider to have global context of the Form class. |
Creating an asymmetric key | Creates an asymmetric public and private key value pair and assigns it a key container name. |
Encrypting a file | Displays a dialog box to select a file for encryption and encrypts the file. |
Decrypting a file | Displays a dialog box to select an encrypted file for decryption and decrypts the file. |
Getting a private key | Gets the full key pair using the key container name. |
Exporting a public key | Saves the key to an XML file with only public parameters. |
Importing a public key | Loads the key from an XML file into the key container. |
Testing the application | Lists procedures for testing this application. |
Prerequisites
You need the following components to complete this walkthrough:
- References to the System.IO and System.Security.Cryptography namespaces.
Creating a Windows Forms Application
Most of the code examples in this walkthrough are designed to be event handlers for button controls. The following table lists the controls required for the sample application and their required names to match the code examples.
Control | Name | Text property (as needed) |
---|---|---|
Button | buttonEncryptFile | Encrypt File |
Button | buttonDecryptFile | Decrypt File |
Button | buttonCreateAsmKeys | Create Keys |
Button | buttonExportPublicKey | Export Public Key |
Button | buttonImportPublicKey | Import Public Key |
Button | buttonGetPrivateKey | Get Private Key |
Label | label1 | Key not set |
OpenFileDialog | openFileDialog1 | |
OpenFileDialog | openFileDialog2 |
Double-click the buttons in the Visual Studio designer to create their event handlers.
Declaring Global Objects
Add the following code to the Form's constructor. Edit the string variables for your environment and preferences.
Creating an Asymmetric Key
This task creates an asymmetric key that encrypts and decrypts the RijndaelManaged key. This key was used to encrypt the content and it displays the key container name on the label control.
Add the following code as the
Click
event handler for the Create Keys
button (buttonCreateAsmKeys_Click
).Encrypting a File
This task involves two methods: the event handler method for the
Encrypt File
button (buttonEncryptFile_Click
) and the EncryptFile
method. The first method displays a dialog box for selecting a file and passes the file name to the second method, which performs the encryption.The encrypted content, key, and IV are all saved to one FileStream, which is referred to as the encryption package.
The
EncryptFile
method does the following:- Creates a RijndaelManaged symmetric algorithm to encrypt the content.
- Creates an RSACryptoServiceProvider object to encrypt the RijndaelManaged key.
- Uses a CryptoStream object to read and encrypt the FileStream of the source file, in blocks of bytes, into a destination FileStream object for the encrypted file.
- Determines the lengths of the encrypted key and IV, and creates byte arrays of their length values.
- Writes the Key, IV, and their length values to the encrypted package.
The encryption package uses the following format:
- Key length, bytes 0 - 3
- IV length, bytes 4 - 7
- Encrypted key
- IV
- Cipher text
You can use the lengths of the key and IV to determine the starting points and lengths of all parts of the encryption package, which can then be used to decrypt the file.
Add the following code as the
Click
event handler for the Encrypt File
button (buttonEncryptFile_Click
).Add the following
EncryptFile
method to the form.Decrypting a File
This task involves two methods, the event handler method for the
Decrypt File
button (buttonDecryptFile_Click
), and the DecryptFile
method. The first method displays a dialog box for selecting a file and passes its file name to the second method, which performs the decryption.The
Decrypt
method does the following:- Creates a RijndaelManaged symmetric algorithm to decrypt the content.
- Reads the first eight bytes of the FileStream of the encrypted package into byte arrays to obtain the lengths of the encrypted key and the IV.
- Extracts the key and IV from the encryption package into byte arrays.
- Creates an RSACryptoServiceProvider object to decrypt the RijndaelManaged key.
- Uses a CryptoStream object to read and decrypt the cipher text section of the FileStream encryption package, in blocks of bytes, into the FileStream object for the decrypted file. When this is finished, the decryption is completed.
Add the following code as the
Click
event handler for the Decrypt File
button.Add the following
DecryptFile
method to the form.Exporting a Public Key
This task saves the key created by the
Create Keys
button to a file. It exports only the public parameters.This task simulates the scenario of Alice giving Bob her public key so that he can encrypt files for her. He and others who have that public key will not be able to decrypt them because they do not have the full key pair with private parameters.
Add the following code as the
Click
event handler for the Export Public Key
button (buttonExportPublicKey_Click
).Importing a Public Key
This task loads the key with only public parameters, as created by the
Export Public Key
button, and sets it as the key container name.This task simulates the scenario of Bob loading Alice's key with only public parameters so he can encrypt files for her.
Add the following code as the
Click
event handler for the Import Public Key
button (buttonImportPublicKey_Click
).Getting a Private Key
This task sets the key container name to the name of the key created by using the
Create Keys
button. The key container will contain the full key pair with private parameters.This task simulates the scenario of Alice using her private key to decrypt files encrypted by Bob.
Add the following code as the
Click
event handler for the Get Private Key
button (buttonGetPrivateKey_Click
).Testing the Application
After you have built the application, perform the following testing scenarios.
To create keys, encrypt, and decrypt
- Click the
Create Keys
button. The label displays the key name and shows that it is a full key pair. - Click the
Export Public Key
button. Note that exporting the public key parameters does not change the current key. - Click the
Encrypt File
button and select a file. - Click the
Decrypt File
button and select the file just encrypted. - Examine the file just decrypted.
- Close the application and restart it to test retrieving persisted key containers in the next scenario.
To encrypt using the public key
- Click the
Import Public Key
button. The label displays the key name and shows that it is public only. - Click the
Encrypt File
button and select a file. - Click the
Decrypt File
button and select the file just encrypted. This will fail because you must have the private key to decrypt.
This scenario demonstrates having only the public key to encrypt a file for another person. Typically that person would give you only the public key and withhold the private key for decryption.
To decrypt using the private key
- Click the
Get Private Key
button. The label displays the key name and shows whether it is the full key pair. - Click the
Decrypt File
button and select the file just encrypted. This will be successful because you have the full key pair to decrypt.
See also
Introduction
We get many queries from people about how to use keys in cryptography and how to represent them. This page is a simple introduction. If you take away nothing else, remember thata password is not a key.
Contents
What is a key?
A definition of a key from ISO/IEC 10116 (2nd edition): 1997 is
A sequence of symbols that controls the operation of a cryptographic transformation (e.g. encipherment, decipherment).
In practice a key is normally a string of bits used by a cryptographic algorithmto transform plain text into cipher text or vice versa. The key should be the only partof the algorithm that it is necessary to keep secret.
Which Cryptographic System Generates Encryption Keys In Windows 7
Key length
The key length is usually expressed in bits, 8 bits to one byte. Bytes are a more convenient form for storing and representing keys because most computer systemsuse a byte as the smallest unit of storage (the strict term for an 8-bit byte is octet). Just remember that most encryption algorithms work withbit strings. It's up to the user to pass them in the required format to the encryption function they are using. That format is generally as an array of bytes, but could be in hexadecimal or base64 format.
In theory, the longer the key, the harder it is to crack encrypted data.The longer the key, however, the longer it takes to carry out encrypion anddecryption operations, although with modern computers, this is not normally an issue.Speed might be an issue with a smart card, for example.
Block cipher encryption algorithms like AES and Blowfish work by taking a fixed-length block of plaintext bits andtransforming it into the same length of ciphertext bits using a key.Blowfish uses a variable key length between 8 and 448 bits long. It is atthe choice of the two parties exchanging data to agree what length they use. Most other block cipher encryption methods have a fixed length key. For example, DES has a64-bit key (but only uses 56 of them) and Triple DES has a 192-bit key (but only uses 168 of them).IDEA uses a 128-bit key.The Advanced Encryption Algorithm (AES) has a choice of three key lengths: 128, 192 or 256 bits.Public key encryption algorithms like RSA typically have key lengths in the order of 1000-2000 bits.Be careful with the difference in key lengths for block cipher algorithms and public key algorithms.According to SP800-57 Part 1 Table 4, a 192-bit Triple DES key is equivalent in security terms to a 2048-bit RSA key, andan AES-128 key is equivalent to a 3072-bit RSA key.
How relevant is key length?
To crack some ciphertext encrypted with a 64-bit key by the brute-force method oftrying everycombination of keys possible means you have 2^64 possible combinationsor 1.8 x 10^19 (that's 18 followed by 18 naughts). You can expect, on the average, to find a correctanswer in half this number of tries. If you have a computer that can carry out one encryptionoperation every millisecond, it will take about 292 million years to find the correct value.Speed up your computer by a million times and it will still take about 3 centuries to solve.The equivalent brute force technique for a 128-bit key will, in theory, take a 'long time', probably past the expected life of the universe.But, in practice, a set of supercomputers operating in parallel can crack a 64-bit key ina relatively short time. If an attacker has access to a large selection of messages all encryptedwith the same key, there are other techniques that can be used to reduce the time to derive the key.
Will other people try and crack my ciphertext?
Your competitors in business and people who you suspect log your encrypted credit card number from the Internet don't usually have these facilities at their disposal. However, if an organisation like the NSA wanted to,they may well be prepared to put such resources into it. We doubt that the NSA or anyone else forthat matter is routinely decrypting all your PGP emails.You are not that important - see SatireWire'svery amusing article Hackers Beg Boring People To Stop Encrypting Email.Security Experts Concur Most of You Have Nothing Worth Encrypting.However, 'they' may well be flagging emails that are sent encrypted andkeeping a copy of them. If some other incriminating evidence comes up about you, they may then go back and try to decrypt them.On the other hand, they could just arrest you and force you to tell themyour password: how long are you prepared to protect your secret love letters when someone is using a thumbscrew on you?How do encryption schemes fail?
Most encryption schemes are cracked not by brute forcetrying of all possible combinations of key bits, but by using otherknowledge about how the sender derived the key. This could be a faultyrandom number generator known to used by the system, or knowledge that theuser derived the key solely from a password of only the letters a to z, or just used simpleEnglish words. Or perhaps by finding out the keystrokes typed on the keyboard bythe user with a keystroke logger, or by bribing (or torturing) someone to give them the key, or by reading the post-it note the user has conveniently left on the side of the computerwith the password written on it.The traps are many and subtle and even the experts get it wrong. Why spend hours trying to pick the expensive security lock when the owner of the house has left a window open?
Strictly, it's not the length of the key, but the 'entropy' in the methodused to derive the key. There is approximately one bit ofentropy in an normal ascii character. If you derive a 128-bit key from a passwordor pass phrase, you will need a very long pass phrase to get enoughtheoretical entropy in the key to match the security of the underlying keylength: Bruce Schneier estimates that you need a 98-character English passphrasefor a 128-bit key. Most people can't be bothered with such a cumbersome passphrase.
Using AES with a 128-bit key should provide adequate security for most purposes. The longer you intend to keep the encrypted data secret, the longer the key you should use, on the principle that cracking techniques will continue to improve over time.Bruce Schneier recommends a 256-bit key for data you intend to keep for 20-30 years.
No one is going to criticise you for using a key that is too long provided your softwarestill performs adequately. However, in our opinion, the biggest danger in using a key that is too large is the falsesense of security it provides to the implementers and users. 'Oh, we have n-million-bit security in our system' may sound impressive in a marketing blurb, but thefact that your private key is not adequately protected or your random number generator is not random or you have used an insecure algorithm may mean that the total security is next to useless.
Which Cryptographic System Generates Encryption Keys Windows 10
Remember it is the security of the total system that counts, including procedures followed by users.
Choice of Algorithm
Whatever you use, use an accepted algorithm: AES, Blowfish, Triple DES,IDEA, etc. Don't try making up your own algorithm; you aren't that good. The only secret should be in the value of thekey. Everything else should be publicly available for scrutiny. Any systemthat is otherwise is known as 'snake oil'.
Password, pass phrase and key
People often get confused between 'password' and 'key'. A password istypically a series of ASCII characters typed at a keyboard, e.g. 'hello123' or 'my secretpass phrase'. This makes it easier for users to remember. They are, ofcourse, much easier to crack because there are significantly fewercombinations to choose from.
A pass phrase is simply a password that consists of several words in a string, e.g. 'she sells sea shells', so the terms 'password' and 'pass phrase' are equivalent for our purposes.In principle, a pass phrase makes it easier for a user to remember a long combinationof characters. In practice, this adds to security only if the pass phrase is somethingknown only to the user. Don't use quotes from famous literature - hackers read them, too.
A key used by an encryption algorithm is a bit string. A 128-bit key willhave exactly 128 bits in it, i.e. 16 bytes. You will often see keys writtenin hexadecimal format where each character represents 4 bits, e.g.'FEDCBA98765432100123456789ABCDEF' represents 16 bytes or 128 bits. The actual bits in thisexample are
There are many, many more combinations of 128 bits thanof combinations of a few simple letters of the alphabet.This is where the security comes in.How should I derive the key?
How you get from the password to the key is one of the tricks to ensuregood, underlying security. One method is to use a one-way hash functionsuch as SHA-1 or MD5. This takes a message of varying length and creates adigest of a fixed length. MD5 produces a digest of 128 bits or 16 bytes; SHA-1 produces one of 160 bits or 20 bytes. (Thanks to Jorge Fabregas for pointing out that an MD5 digest is 128 bits, not 64.)
The same message will always give the samedigest, but it should be impossible (strictly, computationally infeasible)to derive the message from the digest. Well, maybe not. Remember that hackers know the digest values for all the simple passwords: for example,
MD5('password')=5f4dcc3b5aa765d61d8327deb882cf99
.To improve security, we should mix in a few randombytes (a salt) with the message and re-hash it a given number of times to produce abit string to use as a key. Obviously, whatever method you use, you will need to be ableto reproduce the same key given the same password when you come to decrypt your message.
Example 1
We are using an encryption algorithm that uses a 128-bit key. Our userhas entered the ascii string 'abc' as the password they want to use to encrypt their secret data. The data may involve details of secret liaisons that our client is havingwith his mistress,or an important business deal, or the medical history of a patient, or the codeword to trigger a world-wide nuclear war. We don't care about the significance; we are going to apply our encryption algorithm that requires a 128-bit key to transform plain text into cipher text.Our problem is how to derive a key.
The ascii string 'abc' consists of the three bytes with hexadecimal values 61, 62, 63.We need 16 bytes for our key, we only have 3. We could just do a direct conversionand use the key Obviously this does not give us much security as we are only using 24 out of the 128bits. The fact that 'abc' will only take a few seconds to guess anyway is another issue.If we hash this with MD5 we get the following 16 bytes:
If we hash these bytes again, we get:
and so on. Notwithstanding the poor choice of password in the first place, these bit strings could be used as keys in our encryption algorithm.If we only needed a 64-bit key, we could just use the first 8 bytes. If we needed a256-bit key, we could concatenate (join together) the two hash digests and use that.
However, there are limitations in this simple method. True, we have expanded our simplethree-character password into a longer bit string, but if an attacker knows the methodwe have used to derive the key from the password, he, too, can do the same for all possiblecombinations of letters. The key space is still just as small as we started with.An attacker could just prepare a lookup table of hashed results for all the possible combinationsof words in the dictionary and use that.
A good designer should assume that the key derivation method is known to an attacker. It is not good enoughjust to hope it's well hidden. The only secret should be the password itself.
Example 2
There are two standard methods to hinder an attacker's ability to reproduce our key derivation function. The first is salting and the second isstretching where we introducean iteration count. Salting involves mixing in some random data with thepassword. This greatly increases the possible number of keys that could be derivedfrom a given password and prevents an attacker from compiling a dictionaryof pre-computed values. The iteration count specifies that the function must be repeated a given number of times,say, a minimum of 1000. This forces an attacker to go to a lot of extra work when trying out alternatives, but is not particularly onerous for a valid user.
You must be able to communicate the salt and iteration count to the other party so they can reproduce the same key from the password. This informationcan be sent in the clear. The iteration count can be agreed and fixed for all messages,but the seed must be different for each message.
In this example, we start with our password 'abc' but select a random set of 8 bytesto use as a salt (S), say,
and specify that the iteration count (c) is to be 1000. We concatenate our password and salt and compute the hash of this:-
Then we repeat this until we have carried out the hash 1000 timesWe use the final digest 8FD6158BFE81ADD961241D8E4169D411
as the key to encrypt the data.The next time we send a message, we use the same password but a different salt, say,
and specify the iteration count to be 2048. In this case, using the same method as before, the resulting key will beCC584D1EE305FB7EF65926F62E88DFE3
.Note we are not condoning using such a simple combination as 'abc' as a valid password.It is merely used to show the technique.
This password-based encryption algorithm is known as PBKDF1.The Visual Basic code basMD5pbe1.bas shows how to carry out above computations.Thanks to Chris Searl for pointing out an error in an earlier version.
Cryptographic Key Types
Another complication arises with systems set up for oriental characters. We could writea book on this topic (and many people have). Put simply, if your computer is set up for US-English, all the characters you need to display can be representedby a single 8-bit byte. So it is a simple matter to go from the string 'abc' to the three bytes 0x61,0x62 and 0x63 that we can then use to derive our key bit string. When we start using systems set up for oriental characters, things get complicated,and converting a password string into bytes becomes messy. See Cryptography with International Character Setsand Cross-Platform Encryptionfor more information on this topic.Just remember that, in Visual Basic, always use the
Byte
type to do yourcryptographic operations and always convert your password String
type into a Byte
array first. Password-Based Encryption Algorithms
The RSA Laboratories documentPKCS#5: Password-Based Cryptography Specification Version 2.0describes two secure password-based encryption (PBE) algorithms.This Visual Basic code basPBKDF2.bas demonstratesthe use of the PBKDF2 algorithm using the built-in function in ourCryptoSys API package.Hindering brute force password cracking
If we have an application that uses a password to allow users access to sensitiveencrypted data, it is exposed to the possibility that someone may just try every conceivable password until they succeed. There are automated programs out therethat do just that.Most users if left to themselves will choosesimple, easy to remember passwords that considerably reduce the possible number ofcombinations.For some interesting research on this topic seeThe Memorability and Security of Passwords by Ross Anderson and othersfrom Cambridge University.
As a designer there are two simple techniques to use to improve security:
- Three strikes and you're out
- Introduce a delay before responding
In the first technique, you only allow the user three attempts to log in and then shut down the application, or at leastthe user's access screen. This is easy to implement on an EXE application on a PC, but harder todo with a web application where each attempt to log in is a separate event as far as the serveris concerned and people can just keep trying.
In the second technique, you deliberately introduce a short delay of, say, half a second, before confirming or rejecting the user's attempt to log in. The user will hardly noticesuch a short delay, but this will severely hamper a cracker's automated attempt to tryall variations in a short time.
Oh yes, and don't limit your users to ridiculously short passwords.
What's base64 encoding?
'Encoding' simply means converting data from one form to another, notnecessarily encrypted. Just remember that Encoding is not encryption.base64 encoding is a method to convert 8-bit characters to 7-bitcharacters so they can be transferred over the internet. MIME uses this; so does PGP.It's also known as radix 64 encoding. Binary data encoded with base64 encoding looks like
This represents the 8 bytes A base64 string consists of the 64 characters A-Z, a-z, 0-9 and '/' and '+', and can be terminatedby up to two '=' characters for padding.Each four base64 characters represent three bytes. A valid base64 string will always be an exact multiple offour characters long. In practice, programs that decode from base64 will (should) just ignore characters that are notvalid; but if a '=' character is found, it should be taken as indicating the end of the data.
Hexadecimal notation
Hexadecimal means a number expressed in base 16. The convention is that each digitcan be between 0 and 15 in value and is represented by the characters 0-9 and A-F. It does not matter whether the letters are in upper- or lower-case. The 4-bit number that a hexadecimal digit represents is sometimes referred to asa nibble or nybble ('byte', 'nybble', get it?).
Hexadecimal | Decimal | Binary |
0 | 0 | 0000 |
1 | 1 | 0001 |
2 | 2 | 0010 |
3 | 3 | 0011 |
4 | 4 | 0100 |
5 | 5 | 0101 |
6 | 6 | 0110 |
7 | 7 | 0111 |
8 | 8 | 1000 |
9 | 9 | 1001 |
A | 10 | 1010 |
B | 11 | 1011 |
C | 12 | 1100 |
D | 13 | 1101 |
E | 14 | 1110 |
F | 15 | 1111 |
In the C programming language, hexadecimal values are expressed in the form 0x7ABF, where the '0x' signifies a number following in hexadecimal. In Visual Basic, the format is &H7ABF. In Assembler language, the format is 7ABFH.They all mean the same thing.The usual convention is that bits to theleft are the most significant and those to the right are the least significant. This would mean that 7ABF (or 0x7ABF in C or &H7ABF in Visual Basic) would represent thedecimal integer 31423. (Hint: use the Calculator that comes with Windows todo these conversions - use it in Programmer mode.)
Try this in your Visual Basic (VB6) debugger:-This shows how to convert between hexadecimal and decimal format in Visual Basic.Now try this example:-
Now why doesn't the second statement give us what we expect? This is because of thesign bit - Visual Basic 6 uses 'signed' arithmetic and we want to use 'unsigned'.This is a topic for another time. (For the solution, see Binary and Byte Operations in Visual Basic on our Cryptography page.)
What's big-endian and little-endian?
Cryptographic Key Management Software
How your computer actually stores its data is another issue again - there are big-endian computers that store their data with the most significant byte first, and little-endiancomputers that store their data with the least significantbytes first. Unix-based systems are often big-endian. Intel-based Windows computers are little-endian.However, this is only of interest to us if we go poking around looking at howthe bytes are arranged inside our computer memory and, for practical purposes, only serves to confuse an otherwise messy subject. The usual convention is to write out bit strings with the most significant bit first.
Other Information
For an introduction on how to use padding in cryptography, seeUsing Padding in Cryptography.Contact
To comment on this page or ask a question, please send us a message.
This page last updated 14 October 2014