12/18/2020 Php Openssl Generate Symmetric Key
Oct 09, 2019 How to Generate & Use Private Keys using OpenSSL's Command Line Tool These commands generate and use private keys in unencrypted binary (not Base64 “PEM”) PKCS#8 format. The PKCS#8 format is used here because it is the most interoperable format when dealing with software that isn't based on OpenSSL. Apr 25, 2017 Simple Encryption in PHP. Contribute to defuse/php-encryption development by creating an account on GitHub. This is a library for encrypting data with a key or password in PHP. It requires PHP 5.6 or newer and OpenSSL 1.0.1 or newer.
Creating and managing keys is an important part of the cryptographic process. Symmetric algorithms require the creation of a key and an initialization vector (IV). The key must be kept secret from anyone who should not decrypt your data. The IV does not have to be secret, but should be changed for each session. Asymmetric algorithms require the creation of a public key and a private key. The public key can be made public to anyone, while the private key must known only by the party who will decrypt the data encrypted with the public key. This section describes how to generate and manage keys for both symmetric and asymmetric algorithms.
Symmetric Keys
The symmetric encryption classes supplied by the .NET Framework require a key and a new initialization vector (IV) to encrypt and decrypt data. Whenever you create a new instance of one of the managed symmetric cryptographic classes using the parameterless constructor, a new key and IV are automatically created. Anyone that you allow to decrypt your data must possess the same key and IV and use the same algorithm. Generally, a new key and IV should be created for every session, and neither the key nor IV should be stored for use in a later session.
To communicate a symmetric key and IV to a remote party, you would usually encrypt the symmetric key by using asymmetric encryption. Sending the key across an insecure network without encrypting it is unsafe, because anyone who intercepts the key and IV can then decrypt your data. For more information about exchanging data by using encryption, see Creating a Cryptographic Scheme.
The following example shows the creation of a new instance of the TripleDESCryptoServiceProvider class that implements the TripleDES algorithm.
When the previous code is executed, a new key and IV are generated and placed in the Key and IV properties, respectively.
Sometimes you might need to generate multiple keys. In this situation, you can create a new instance of a class that implements a symmetric algorithm and then create a new key and IV by calling the GenerateKey and GenerateIV methods. The following code example illustrates how to create new keys and IVs after a new instance of the symmetric cryptographic class has been made.
When the previous code is executed, a key and IV are generated when the new instance of TripleDESCryptoServiceProvider is made. Another key and IV are created when the GenerateKey and GenerateIV methods are called.
Asymmetric Keys
The .NET Framework provides the RSACryptoServiceProvider and DSACryptoServiceProvider classes for asymmetric encryption. These classes create a public/private key pair when you use the parameterless constructor to create a new instance. Asymmetric keys can be either stored for use in multiple sessions or generated for one session only. While the public key can be made generally available, the private key should be closely guarded.
A public/private key pair is generated whenever a new instance of an asymmetric algorithm class is created. After a new instance of the class is created, the key information can be extracted using one of two methods:
Both methods accept a Boolean value that indicates whether to return only the public key information or to return both the public-key and the private-key information. An RSACryptoServiceProvider class can be initialized to the value of an RSAParameters structure by using the ImportParameters method.
Asymmetric private keys should never be stored verbatim or in plain text on the local computer. If you need to store a private key, you should use a key container. For more on how to store a private key in a key container, see How to: Store Asymmetric Keys in a Key Container.
The following code example creates a new instance of the RSACryptoServiceProvider class, creating a public/private key pair, and saves the public key information to an RSAParameters structure.
See also
The libcrypto library within OpenSSL provides functions for performing symmetric encryption and decryption operations across a wide range of algorithms and modes. This page walks you through the basics of performing a simple encryption and corresponding decryption operation.
In order to perform encryption/decryption you need to know:
This page assumes that you know what all of these things mean. If you don't then please refer to Basics of Encryption.
The complete source code of the following example can be downloaded as evp-symmetric-encrypt.c.
Setting it up[edit]
The code below sets up the program. In this example we are going to take a simple message ('The quick brown fox jumps over the lazy dog'), and then encrypt it using a predefined key and IV. In this example the key and IV have been hard coded in - in a real situation you would never do this! Following encryption we will then decrypt the resulting ciphertext, and (hopefully!) end up with the message we first started with. This program expects two functions to be defined: 'encrypt' and 'decrypt'. We will define those further down the page. Note that this uses the auto-init facility in 1.1.0.
The program sets up a 256 bit key and a 128 bit IV. This is appropriate for the 256-bit AES encryption that we going to be doing in CBC mode. Make sure you use the right key and IV length for the cipher you have selected, or it will go horribly wrong!! The IV should be random for CBC mode.
We've also set up a buffer for the ciphertext to be placed in. It is important to ensure that this buffer is sufficiently large for the expected ciphertext or you may see a program crash (or potentially introduce a security vulnerability into your code). Note: The ciphertext may be longer than the plaintext (e.g. if padding is being used).
We're also going to need a helper function to handle any errors. This will simply dump any error messages from the OpenSSL error stack to the screen, and then abort the program.
Encrypting the message[edit]
So now that we have set up the program we need to define the 'encrypt' function. This will take as parameters the plaintext, the length of the plaintext, the key to be used, and the IV. We'll also take in a buffer to put the ciphertext in (which we assume to be long enough), and will return the length of the ciphertext that we have written.
Encrypting consists of the following stages:
During initialisation we will provide an EVP_CIPHER object. In this case we are using EVP_aes_256_cbc(), which uses the AES algorithm with a 256-bit key in CBC mode. Refer to Working with Algorithms and Modes for further details.
Decrypting the Message[edit]
Finally we need to define the 'decrypt' operation. This is very similar to encryption and consists of the following stages:Decrypting consists of the following stages:
![]()
Again through the parameters we will receive the ciphertext to be decrypted, the length of the ciphertext, the key and the IV. We'll also receive a buffer to place the decrypted text into, and return the length of the plaintext we have found.
Note that we have passed the length of the ciphertext. This is required as you cannot use functions such as 'strlen' on this data - its binary! Similarly, even though in this example our plaintext really is ASCII text, OpenSSL does not know that. In spite of the name plaintext could be binary data, and therefore no NULL terminator will be put on the end (unless you encrypt the NULL as well of course).
Here is the decrypt function:
Ciphertext Output[edit]
If all goes well you should end up with output that looks like the following:
Openssl Generate Crt And Key
For further details about symmetric encryption and decryption operations refer to the OpenSSL documentation Manual:EVP_EncryptInit(3).
Padding[edit]
OpenSSL uses PKCS padding by default. If the mode you are using allows you to change the padding, then you can change it with EVP_CIPHER_CTX_set_padding. From the man page:
EVP_CIPHER_CTX_set_padding() enables or disables padding. By default encryption operations are padded using standard block padding and the padding is checked and removed when decrypting. If the pad parameter is zero then no padding is performed, the total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur...
Openssl Generate Public Private Key
PKCS padding works by adding n padding bytes of value n to make the total length of the encrypted data a multiple of the block size. Padding is always added so if the data is already a multiple of the block size n will equal the block size. For example if the block size is 8 and 11 bytes are to be encrypted then 5 padding bytes of value 5 will be added...
If padding is disabled then the decryption operation will only succeed if the total amount of data decrypted is a multiple of the block size.
C++ Programs[edit]
Questions regarding how to use the EVP interfaces from a C++ program arise on occasion. Generally speaking, using the EVP interfaces from a C++ program is the same as using them from a C program.
You can download a sample program using EVP symmetric encryption and C++11 called evp-encrypt.cxx. The sample uses a custom allocator to zeroize memory, C++ smart pointers to manage resources, and provides a secure_string using basic_string and the custom allocator. You need to use g++ -std=c++11 ... to compile it because of std::unique_ptr.
You should also ensure you configure an build with -fexception to ensure C++ exceptions pass as expected through C code. And you should avoid other flags, like -fno-exceptions and -fno-rtti.
The program's main simply encrypts and decrypts a string using AES-256 in CBC mode:
And the encryption routine is as follows. The decryption routine is similar:
Php Openssl Generate Symmetric Key VsNotes on some unusual modes[edit]
Worthy of mention here is the XTS mode (e.g. EVP_aes_256_xts()). This works in exactly the same way as shown above, except that the 'tweak' is provided in the IV parameter. A further 'gotcha' is that XTS mode expects a key which is twice as long as normal. Therefore EVP_aes_256_xts() expects a key which is 512-bits long.
Authenticated encryption modes (GCM or CCM) work in essentially the same way as shown above but require some special handling. See EVP Authenticated Encryption and Decryption for further details.
Use Openssl To Generate Key PairSee also[edit]Openssl Generate Rsa Private Key
Retrieved from 'https://wiki.openssl.org/index.php?title=EVP_Symmetric_Encryption_and_Decryption&oldid=2787'
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
December 2020
Categories |