Перейти к содержимому

Pkcs 7 что это

  • автор:

An Introduction to Digital Signatures and PKCS #7

In many parts of the world, including the European Union and the United States, businesses have adopted digital signing as a way to implement electronic signatures that are considered legally binding. This article introduces digital signatures, digital certificates, and the relationship between digital signatures and PKCS #7.

Digital Signature

A digital signature is proof of the authenticity of digital messages, files, executables, documents, etc. in modern communication by employing strong cryptographic techniques such as encryption and hashing. A unique digital ID (and a signing key) are required to create a digital signature. Digital IDs or certificates are based on asymmetric (or public key) cryptography, which uses key pairs (a combination of public and private keys). Public keys are openly distributed among the communicating entities, and the private (signing) keys are kept secret. The most common public key algorithm used is RSA.

Digital Certificate

A digital certificate is an electronic document used to prove ownership of a public key . The certificate includes the public key, information about its owner’s identity and associated permissions.

Certificates provide the foundation for a PKI (public key infrastructure). Certificates are electronic representations of users, computers, network devices, or services. They are given out by a CA (Certificate Authority) and are linked to a pair of public and private keys. The current standard being used for digital certificates is X.509, as defined in RFC 5280. Some of the main parameters that exist in a certificate are:

  1. Certificate serial number
  2. Name of the certificate issuer
  3. Certificate issuer’s signature algorithm identifier
  4. Validity period
  5. Public key

Services provided by Digital Signature

A digital signature is basically a small block of data which is attached to the message to deliver the following security services:

Process of Digital Signing and Verification

The process of digital signing and verification incorporates three steps:

  1. Key Generation : A key pair (private and public key) is generated by employing a public key algorithm such as RSA.
  2. Digital Signature Generation : Compute the cryptographic hash of the input file or message by using a secure hashing algorithm such as SHA-256, SHA-384, SHA-512 or Whirlpool etc. The computed hash is encrypted by the private key of sender resulting in the digital signature. The digital signature is sent along with the original file for its verification by the receiver.
  3. Digital Signature Verification : Sender computes the cryptographic hash of the received file or message by using the same hashing algorithm. Sender decrypts the digital signature by using the public key of the sender to get the hash sent by the sender. If the decrypted hash is exactly same as the computed hash of the received file, it means that digital signature is verified and data was not tampered with during transit.

Relationship between PKCS #7 Standard and Digital Signatures

PKCS #7 named as “Cryptographic Message Syntax Standard” is one the most famous and extensively used standard from the series of PKCS (Public Key Cryptography Standards) by RSA Security LLC. PKCS #7 is the specific standard used for generation and verification of digital signatures and certificates managed by a PKI (Public Key Infrastructure). This standard served as the basis for the S/MIME (Secure/Multipurpose Internet Mail Extensions) standard. PKCS #7 proposes a broad-spectrum syntax and format for creation of digital signatures which is elaborated in detail in RFC 2315. It also allows compatibility with Privacy-Enhanced Mail (PEM) format which is the default and most commonly used file format for storage and sharing of crypto keys and digital certificates. PKCS #7 allows PEM compatible signed-data to be converted into PEM messages.

When using PKCS #7, the result is the exportation of one type “ContentInfo”, in addition to the various object identifiers that are produced. Within this method, there are six general content types:

  1. Data
  2. Signed Data
  3. Enveloped Data
  4. Signed-and-enveloped data
  5. Digested data
  6. Encrypted data

These types are classified into two classes:

  1. Base : contains content types with no cryptographic enhancements. This is used only for the data content type.
  2. Enhanced : contains content types that contain encrypted data or other cryptographic enhancements. The remaining five types fall under this class.

The content types that fall under the enhanced class use encapsulation to encrypt data. These types are prepared with a single pass through indefinite-length BER encoding and are subsequently processed in a single pass using any BER encoding. This is useful when processing data from other processes. A sample S/MIME digital signature created by the private key is shown in the following figure:

PKCS 7 instructions screenshot 1 (general info)

More details of the signature such as version digest algorithm, signature algorithm, content type, signing time and encryption certificate are shown in the following figure:

PKCS 7 instructions screenshot 2 (details)

Conclusion

We have seen how there is a comprehensive set of standards and techniques that mean digital signatures have a very well established framework. Building upon this, regulations such as eIDAS (in the EU) and UETA and E-SIGN ( in the USA) raise the game further by allowing digital signatures entirely equal legal status to traditional “wet” signatures. Specialist security companies, like Cryptomathic, have a strong track record of deploying very dependable, large-scale remote digital signature solutions that fulfill all the strict criteria of the regulations (with eIDAS being the most comprehensive and stringent).

Download white paper

References

    (2014-today), by Ashiq JA, Asim Mehmood, Guillaume Forget, Jan Kjaersgaard , Peter Landrock , Torben Pedersen, Dawn M. Turner, and more (2014-today), by Heather Walker, Luis Balbas, Guillaume Forget, Jan Kjaersgaard, Dawn M. Turner, and more
  • Selected articles on eIDAS (2014-17), by Heather Walker, Guillaume Forget, Jan Kjaersgaard, Dawn M. Turner and more
  • PKCS #7: Cryptographic Message Syntax Version 1.5 (1998), by B.Kaliski, RSA Laboratories

    (2014) by the European Parliament and the European Commission

Uniform Electronic Transactions Act (2000), as an example the publication by the State of Virginia

So What Is PKCS#7?

Prof Bill Buchanan OBE

A symmetric key block cipher, such as AES and DES, uses a defined block size -and which stores a given number of bytes. These blocks are typically either 64-bits (8 bytes) or 128 bits (16 bytes). As we cannot fill all of the blocks, we must pad the last block. PKCS #7 (Cryptographic Message Syntax) is a standard padding method that determines the number of padding bytes and then ads that as a value. For example, for a 128-bit block size, and if we have “testing”, then there are seven bytes (for ASCII coding) that represent the data, and we then have 9 (0x09) padding values. The padding block becomes:

and “testing1” as:

For a 64-bit block, we only have one padding bytes, thus the padding value is:

For “testing1”, we will require another block, and with eight padding bytes:

PKCS 7: один из самых популярных стандартов для защиты данных

PKCS #7 (Cryptographic Message Syntax Standard) — это стандарт криптографического синтаксиса сообщений, который описывает форматы для обмена информацией в форме цифровых сертификатов, шифрования, электронной подписи и других криптографических операций.

Формат PKCS #7 обычно используется в Интернете и в рамках открытых сетей для безопасного обмена информацией. Этот стандарт предоставляет надежное и безопасное средство для защиты информации от несанкционированного доступа или изменения.

Пример кода на языке программирования Java, используя библиотеку BouncyCastle, показывает, как можно создать объект PKCS #7 и получить его содержимое:

В этом примере мы используем класс `CMSSignedDataGenerator` для создания объекта PKCS #7. Мы передаем данные для подписи через класс `CMSProcessableByteArray`, а затем указываем, какую подпись и сертификаты мы хотим использовать, в этом случае, мы используем приватный ключ и сертификат с помощью метода `TestUtils.getPrivateKey()` и `TestUtils.getCertificate()`. После того, как `CMSSignedDataGenerator` создаст подписанный объект PKCS #7, мы можем вызвать метод `getEncoded()` для получения байтового представления этого объекта.

Это только пример, и реализация PKCS #7 может отличаться в различных языках программирования. Однако основные принципы работы с PKCS #7 идеально описывают этот стандарт, что поможет разработчикам различных приложений использовать его в своих целях.

SAP Cloud Integration: Understanding PKCS #7/CMS Standard

This blog post tries to explain in simple words the PKCS #7 and CMS Standards and its relevance for SAP Cloud Integration (CPI).

SAP Cloud Integration provides functionality to automatically add security features to our messages (so-called message-level security).
We don’t need to worry much about the formats and standards used to encrypt or sign the messages.
However, when it comes to specify the configuration options, we start wondering what they mean.
Fortunately, we find the signer and encryptor blogs in the community, which explain the settings.
However, they’re not going into detail about the standard itself.
So let me try to explain the standard with my own simple words.
Note: I’ve tried to explain all of those tedious security-related terms, in case anything’s missing, please refer to the Security Glossary Blog.

Overview

We’ll introduce into the topic along with the following sections:

History

How I imagine that it started:

Timmy from Texas wanted to share some secret info with his friend Taku in Tokyo.
So he encrypted a message and sent it to Taku.
Taku was unable to decrypt and read the message.
So Timmy travelled to Tokyo to enjoy some food and to explain the way how he encrypts and packages his messages.
Afterwards, Taku in Tokyo was able to decrypt and read all messages (even before breakfast).
Some time later, same situation happened with his friend Toto in Togo.
Although the food is said to be great, Timmy decided not to travel, but to invite his friends for a conference at home.
They had international food, late-night discussions and at the end, they agreed on a common way of sending secure messages.
As a consequence, everybody in the world can send secure messages and the recipients can understand the message, as long as they follow that agreement.

Does that make sense?
Really makes sense, especially the section about the international food (which didn’t make it into the specification).

What do we learn from this story?
People communicating with each other need to agree on some basic principles:
– How encryption is done, which steps in which order
– which algorithm is used
– Certificate information to ensure authentication
– Info about sender
– Fingerprint
– And finally: where is that information stored

PKCS #7

While that story is purely fantasy, these needs were captured in reality by a company called RSA Security LLC in the 1990s.
This company designed security standards and collected them in a series of standards called PKCS, which stands for Public Key Cryptography Standards.

What is a Standard?
In my simple words: Experts from all over the world come together to “agree” on a way of doing something.
The result is a guideline and signed as agreement by the experts.
That agreement on a guideline is published as “Standard” and can be maintained by an organization, for instance IETF (Internet Engineering Task Force).

What is PKCS #7?
The seventh PKCS standard was dedicated to describe a way of securely transmitting messages over the internet.
This seventh one is called Cryptographic Message Syntax.
The latest version is 1.5 and can be found here, the RFC number is 2315.

What is RFC?
It stands for “Request for Comments” and is typically a document containing a specification.
Usually created by international volunteers and maintained by IETF, has gone through several review processes. After agreement, a number is assigned and it is published (and further maintained) via the rfc-editor, to which links point.

What dies the PKCS #7 standard say?
The specification doesn’t contain concrete commands or proposal for usage of e.g. a specific algorithm like AES.
The sender of a message can encrypt it with whatever algorithm, but the standard specifies where the information about the used algorithm is maintained. As such, the recipient can look up which algorithm he needs to use for decryption.
Like this, there’s multiple information and types of information that need to be sent along with the message.

What Information?
First of all: Do we want to encrypt the message? Or do we want to sign the message? Or both together?
As an example, if we want to send a message and sign it, we will refer to the section of the spec called “Signed-data”.
We learn that the PKCS #7 standard defines different ways of securing messages and gives them a name. These are the “types” or “content types”.
The following content types are defined in PKCS #7:

  1. Data
  2. Signed Data
  3. Enveloped Data
  4. Signed-and-enveloped data
  5. Digested data
  6. Encrypted data

Short info:
1. The first one is just any data (text or image or whatever)
It is specified, because the other types refer to it.
2. Signed Data means that a digital signature is created on the message.
3. Enveloped Data
The message is encrypted with a symmetric key that is generated on the fly.
This key is encrypted with asymmetric key pair.
The content and the key and certificate and fingerprint, etc
there are many infos that need to be sent to the receiver.
Each info is structured and referred to via a content type.
All of it stored in an envelope, that’s the reason for the name.
4. Signed-and-enveloped data
Means that both, signing and encrypting is done in one step.
5. Digested data refer to just the hash and the content
6. Encrypted data refers to the encrypted data

How does it work?
So if we have a closer look at e.g. the SignedData, we will wonder:
How does the receiver know that the received message is structured in a SignedData-way?
How does he know which algorithm to choose for decrypting the digest?
How does he get hold of the required certificate for decrypting
How does he know that the included certificate is correct and valid?
Once decrypted, how does he get a hold of the digest and which algorithm to use?
If he wants to validate the time, when the signature was created, how does he find it?

The answer is:
Everything that is required, is contained in the data structure, which I like to call “package” (like a classic package that is sent with FedEx).
So if we send a message according to PKCS #7, it is like sending a package, containing multiple artifacts and informations.
And the PKCS#7 standard is like a paper which is attached to the package, like a table of content, such that the receiver knows where to find the corresponding info for each unpackage-step.

How to find all the info?
We can see that there are many elements defined in the spec and each element needs to uniquely be targeted.
So it is necessary to assign an ID to each element, or better: to each type (this is PKCS7-language).
This is done in form of OIDs.

What is an OID?
This is the abbreviation of “Object Identifier”.

What Object Identifier?
This is the attempt of giving everything in the world a unique identifier, which allows to describe it and exactly refer to it.
OIDs are structured in a tree hierarchy and the flattened notation is a chain of numbers separated by dots.
Example: 1.2.840.113549.1.7.1
If you encounter such an OID, you can go ahead and search for it in this repository web page.
Then enjoy the description of each tree node and see the rfc that defined the OID, resp child nodes.

So to pick one example from above:
The time of the signature is an element in a list of “Signed Attributes” and has the OID 1.2.840.113549.1.9.5 , which can be found in the spec.

How does a structure look like?

Below I’ve listed an excerpt from the type structure defined by PKCS#7:

SignedData
digestAlgorithms
encapContentInfo
certificates
crls
signerInfos
digestAlgorithm
signedAttrs
signatureAlgorithm
signature
unsignedAttrs

The element “encapContentInfo” contains the actual message content, which stays encapsulated in the PKCS7-package. It contains 2 sub-elements: the content itself and the type of the content.
The element “crls” stands for a list CRLs (Certificate Revocation List) and is optional.

Below diagram tries to illustrate how a PKCS#7-based message could look like:

We can see an envelope representing the message.
The message contains the actual content, including an info about its content type.
The message also contains the certificate, as well as the info about the certificate (serial number, the owner, etc).
Furthermore, we can see that the SignerInfo is again a structured data type which contains artifacts like the digital signature as well as metadata about the signature (algorithm), etc
And so on.

Can we see a real-life example?
Sure, see below a beautiful real-life PKCS#7-structure.

Coming to the more important term.

What is CMS?
CMS stands for Cryptographic Message Syntax which is the same name as the name of the PKCS #7 standard.
In fact, it is the same, just different organization.
As we’ve learned above, PKCS #7 was defined by a company, then it was handed over to the IETF in 1999 and renamed to CMS.
Some improvements were done and the current version of the CMS standard was published as RFC5652 in 2009.

What’s the difference to PKCS number 7?
Major difference to PKCS#7 v 1.5 :
The type Signed-and-enveloped data was removed and the type Authenticated-Data (MAC) was added.

What is the strange look of the specs?
The CMS spec uses ASN 1 which stands for Abstract Syntax Notation One.
It is a standard maintained by ITU (International Telecommunication Union) and describes a language for declaring data structures.

Tool Support

The last question would be:

How to do it in practice?
The processes of cryptographically securing messages and putting all together and dealing with binary content, etc…. all this cannot be done by humans.
Developers can use cryptography libraries like Java IAIK, Bouncy Castle or OpenSSL (c-libs).
For end users, there are tools like OpenSSL command line tools.
For Low-Code users, there’s SAP Cloud Integration, which supports 3 types:
Signed-Data
Enveloped-Data
Signed-and-Enveloped-Data
As we know, the last one was defined in PKCS #7 and omitted later in CMS.
SAP Cloud Integration allows the user to encrypt, decrypt, sign, verify messages based on CMS and PKCS #7.
The user only needs to place a shape in the graphical editor and everything will work out of the box.
However, to understand what’s happening or to understand the many possible configuration options, some blog posts are useful.
I hope.

Example Structure

Blow CMS structure was created by OpenSSL which has a parameter for printing the CMS structure to the console or to a file.
The example was taken from a message with digital signature and the content plus certificate are included.
For better readability, I’ve shortened some parts.

Key Takeaways

Basically, the PKCS #7 / CMS standard has 2 purposes:

  • define a fix structure
    So the sender will store all required information and data in a structured way
    And the receiver knows where to grab the required info from
  • define types
    So when the sender creates artifacts (like signature, key) he knows how to classify them
    And the receiver knows what kind of artifacts are contained in the package and how to read them and apply the info

Next Steps

After going through the foundation for understanding the Standards, we’re prepared for using and understanding the Integration Flow Designer of SAP Cloud Integration.
And here are the corresponding blog posts:
Understanding the PKCS #7 / CMS Signer
Understanding the PKCS #7 / CMS Encryptor

Links

CMS
The CMS spec can be found here or here and even here
Wikipedia: CMS, Cryptographic Message Syntax
The spec for PKCS #7 can be found here.
S/MIME builds on top of CMS
CMS extension for CompressedData type

OID:
Wikipedia:OID, Object Identifier
Web-tool to search for OIDs

OpenSSL
Official list of unofficial binaries download page
Docu home
Docu for cms command

Understanding the PKCS #7 / CMS Signer
Understanding the PKCS #7 / CMS Encryptor
Security Glossary Blog

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *