본문 바로가기

전체 글

RFC3852 - Cryptographic Message Syntax(CMS)

2009. 7. 30.

RFC3852 - Cryptographic Message Syntax (CMS)

 

Network Working Group                                         R. Housley
Request for Comments: 3852                                Vigil Security
Obsoletes: 3369                                                July 2004
Category: Standards Track

                   Cryptographic Message Syntax (CMS)

Status of this Memo

   This document specifies an Internet standards track protocol for the
   Internet community, and requests discussion and suggestions for
   improvements.  Please refer to the current edition of the "Internet
   Official Protocol Standards" (STD 1) for the standardization state
   and status of this protocol.  Distribution of this memo is unlimited.

Copyright Notice

   Copyright (C) The Internet Society (2004).

Abstract

   This document describes the Cryptographic Message Syntax (CMS).  This
   syntax is used to digitally sign, digest, authenticate, or encrypt
   arbitrary message content.

Table of Contents

   1.   Introduction. . . . . . . . . . . . . . . . . . . . . . . . .  3
        1.1.   Evolution of the CMS . . . . . . . . . . . . . . . . .  3
               1.1.1.  Changes Since PKCS #7 Version 1.5. . . . . . .  3
               1.1.2.  Changes Since RFC 2630 . . . . . . . . . . . .  4
               1.1.3.  Changes Since RFC 3369 . . . . . . . . . . . .  4
        1.2.  Terminology . . . . . . . . . . . . . . . . . . . . . .  5
        1.3.  Version Numbers . . . . . . . . . . . . . . . . . . . .  5
   2.   General Overview. . . . . . . . . . . . . . . . . . . . . . .  5
   3.   General Syntax  . . . . . . . . . . . . . . . . . . . . . . .  6
   4.   Data Content Type . . . . . . . . . . . . . . . . . . . . . .  6
   5.   Signed-data Content Type. . . . . . . . . . . . . . . . . . .  7
        5.1.   SignedData Type. . . . . . . . . . . . . . . . . . . .  8
        5.2.   EncapsulatedContentInfo Type . . . . . . . . . . . . . 10
               5.2.1.   Compatibility with PKCS #7. . . . . . . . . . 11
        5.3.   SignerInfo Type. . . . . . . . . . . . . . . . . . . . 12
        5.4.   Message Digest Calculation Process . . . . . . . . . . 14
        5.5.   Signature Generation Process . . . . . . . . . . . . . 15
        5.6.   Signature Verification Process . . . . . . . . . . . . 15
   6.   Enveloped-data Content Type . . . . . . . . . . . . . . . . . 16
        6.1.   EnvelopedData Type . . . . . . . . . . . . . . . . . . 17

        6.2.   RecipientInfo Type . . . . . . . . . . . . . . . . . . 19
               6.2.1.   KeyTransRecipientInfo Type. . . . . . . . . . 20
               6.2.2.   KeyAgreeRecipientInfo Type. . . . . . . . . . 21
               6.2.3.   KEKRecipientInfo Type . . . . . . . . . . . . 24
               6.2.4.   PasswordRecipientInfo Type. . . . . . . . . . 25
               6.2.5.   OtherRecipientInfo Type . . . . . . . . . . . 26
        6.3.   Content-encryption Process . . . . . . . . . . . . . . 26
        6.4.   Key-encryption Process . . . . . . . . . . . . . . . . 27
   7.   Digested-data Content Type. . . . . . . . . . . . . . . . . . 27
   8.   Encrypted-data Content Type . . . . . . . . . . . . . . . . . 28
   9.   Authenticated-data Content Type . . . . . . . . . . . . . . . 29
        9.1.   AuthenticatedData Type . . . . . . . . . . . . . . . . 30
        9.2.   MAC Generation . . . . . . . . . . . . . . . . . . . . 32
        9.3.   MAC Verification . . . . . . . . . . . . . . . . . . . 33
   10.  Useful Types. . . . . . . . . . . . . . . . . . . . . . . . . 33
        10.1.  Algorithm Identifier Types . . . . . . . . . . . . . . 33
               10.1.1.  DigestAlgorithmIdentifier . . . . . . . . . . 34
               10.1.2.  SignatureAlgorithmIdentifier. . . . . . . . . 34
               10.1.3.  KeyEncryptionAlgorithmIdentifier. . . . . . . 34
               10.1.4.  ContentEncryptionAlgorithmIdentifier. . . . . 34
               10.1.5.  MessageAuthenticationCodeAlgorithm. . . . . . 35
               10.1.6.  KeyDerivationAlgorithmIdentifier. . . . . . . 35
        10.2.  Other Useful Types . . . . . . . . . . . . . . . . . . 35
               10.2.1.  RevocationInfoChoices . . . . . . . . . . . . 35
               10.2.2.  CertificateChoices. . . . . . . . . . . . . . 36
               10.2.3.  CertificateSet. . . . . . . . . . . . . . . . 37
               10.2.4.  IssuerAndSerialNumber . . . . . . . . . . . . 37
               10.2.5.  CMSVersion. . . . . . . . . . . . . . . . . . 38
               10.2.6.  UserKeyingMaterial. . . . . . . . . . . . . . 38
               10.2.7.  OtherKeyAttribute . . . . . . . . . . . . . . 38
   11.  Useful Attributes . . . . . . . . . . . . . . . . . . . . . . 38
        11.1.  Content Type . . . . . . . . . . . . . . . . . . . . . 39
        11.2.  Message Digest . . . . . . . . . . . . . . . . . . . . 39
        11.3.  Signing Time . . . . . . . . . . . . . . . . . . . . . 40
        11.4.  Countersignature . . . . . . . . . . . . . . . . . . . 41
   12.  ASN.1 Modules . . . . . . . . . . . . . . . . . . . . . . . . 42
        12.1.  CMS ASN.1 Module . . . . . . . . . . . . . . . . . . . 43
        12.2.  Version 1 Attribute Certificate ASN.1 Module . . . . . 50
   13.  References  . . . . . . . . . . . . . . . . . . . . . . . . . 51
        13.1.  Normative References . . . . . . . . . . . . . . . . . 51
        13.2.  Informative References . . . . . . . . . . . . . . . . 52
   14.  Security Considerations . . . . . . . . . . . . . . . . . . . 53
   15.  Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . 55
   16.  Author's Address. . . . . . . . . . . . . . . . . . . . . . . 55
   17.  Full Copyright Statement. . . . . . . . . . . . . . . . . . . 56

1.  Introduction

   This document describes the Cryptographic Message Syntax (CMS).  This
   syntax is used to digitally sign, digest, authenticate, or encrypt
   arbitrary message content.

   The CMS describes an encapsulation syntax for data protection.  It
   supports digital signatures and encryption.  The syntax allows
   multiple encapsulations; one encapsulation envelope can be nested
   inside another.  Likewise, one party can digitally sign some
   previously encapsulated data.  It also allows arbitrary attributes,
   such as signing time, to be signed along with the message content,
   and provides for other attributes such as countersignatures to be
   associated with a signature.

   The CMS can support a variety of architectures for certificate-based
   key management, such as the one defined by the PKIX working group
   [PROFILE].

   The CMS values are generated using ASN.1 [X.208-88], using BER-
   encoding [X.209-88].  Values are typically represented as octet
   strings.  While many systems are capable of transmitting arbitrary
   octet strings reliably, it is well known that many electronic mail
   systems are not.  This document does not address mechanisms for
   encoding octet strings for reliable transmission in such
   environments.

1.1.  Evolution of the CMS

   The CMS is derived from PKCS #7 version 1.5, which is documented in
   RFC 2315 [PKCS#7].  PKCS #7 version 1.5 was developed outside of the
   IETF; it was originally published as an RSA Laboratories Technical
   Note in November 1993.  Since that time, the IETF has taken
   responsibility for the development and maintenance of the CMS.
   Today, several important IETF standards-track protocols make use of
   the CMS.

   This section describes the changes that the IETF has made to the CMS
   in each of the published versions.

1.1.1.  Changes Since PKCS #7 Version 1.5

   RFC 2630 [CMS1] was the first version of the CMS on the IETF
   standards track.  Wherever possible, backward compatibility with PKCS
   #7 version 1.5 is preserved; however, changes were made to
   accommodate version 1 attribute certificate transfer and to support
   algorithm independent key management.  PKCS #7 version 1.5 included

   support only for key transport.  RFC 2630 adds support for key
   agreement and previously distributed symmetric key-encryption key
   techniques.

1.1.2.  Changes Since RFC 2630

   RFC 3369 [CMS2] obsoletes RFC 2630 [CMS1] and RFC 3211 [PWRI].
   Password-based key management is included in the CMS specification,
   and an extension mechanism to support new key management schemes
   without further changes to the CMS is specified.  Backward
   compatibility with RFC 2630 and RFC 3211 is preserved; however,
   version 2 attribute certificate transfer is added, and the use of
   version 1 attribute certificates is deprecated.

   S/MIME v2 signatures [OLDMSG], which are based on PKCS#7 version 1.5,
   are compatible with S/MIME v3 signatures [MSG], which are based on
   RFC 2630.  However, there are some subtle compatibility issues with
   signatures based on PKCS #7 version 1.5.  These issues are discussed
   in section 5.2.1.  These issues remain with the current version of
   the CMS.

   Specific cryptographic algorithms are not discussed in this document,
   but they were discussed in RFC 2630.  The discussion of specific
   cryptographic algorithms has been moved to a separate document
   [CMSALG].  Separation of the protocol and algorithm specifications
   allows the IETF to update each document independently.  This
   specification does not require the implementation of any particular
   algorithms.  Rather, protocols that rely on the CMS are expected to
   choose appropriate algorithms for their environment.  The algorithms
   may be selected from [CMSALG] or elsewhere.

1.1.3.  Changes Since RFC 3369

   This document obsoletes RFC 3369 [CMS2].  As discussed in the
   previous section, RFC 3369 introduced an extension mechanism to
   support new key management schemes without further changes to the
   CMS.  This document introduces a similar extension mechanism to
   support additional certificate formats and revocation status
   information formats without further changes to the CMS.  These
   extensions are primarily documented in section 10.2.1 and section
   10.2.2.  Backward compatibility with earlier versions of the CMS is
   preserved.

   The use of version numbers is described in section 1.3.

   Since the publication of RFC 3369, a few errata have been noted.
   These errata are posted on the RFC Editor web site.  These errors
   have been corrected in this document.

   The text in section 11.4 that describes the counter signature
   unsigned attribute is clarified.  Hopefully the revised text is
   clearer about the portion of the SignerInfo signature that is covered
   by a countersignature.

1.2.  Terminology

   In this document, the key words MUST, MUST NOT, REQUIRED, SHOULD,
   SHOULD NOT, RECOMMENDED, MAY, and OPTIONAL are to be interpreted as
   described in [STDWORDS].

1.3.  Version Numbers

   Each of the major data structures includes a version number as the
   first item in the data structure.  The version numbers are intended
   to avoid ASN.1 decode errors.  Some implementations do not check the
   version number prior to attempting a decode, and if a decode error
   occurs, then the version number is checked as part of the error
   handling routine.  This is a reasonable approach; it places error
   processing outside of the fast path.  This approach is also forgiving
   when an incorrect version number is used by the sender.

   Most of the initial version numbers were assigned in PKCS #7 version
   1.5.  Others were assigned when the structure was initially created.
   Whenever a structure is updated, a higher version number is assigned.
   However, to ensure maximum interoperability the higher version number
   is only used when the new syntax feature is employed.  That is, the
   lowest version number that supports the generated syntax is used.

2.  General Overview

   The CMS is general enough to support many different content types.
   This document defines one protection content, ContentInfo.
   ContentInfo encapsulates a single identified content type, and the
   identified type may provide further encapsulation.  This document
   defines six content types: data, signed-data, enveloped-data,
   digested-data, encrypted-data, and authenticated-data.  Additional
   content types can be defined outside this document.

   An implementation that conforms to this specification MUST implement
   the protection content, ContentInfo, and MUST implement the data,
   signed-data, and enveloped-data content types.  The other content
   types MAY be implemented.

   As a general design philosophy, each content type permits single pass
   processing using indefinite-length Basic Encoding Rules (BER)
   encoding.  Single-pass operation is especially helpful if content is
   large, stored on tapes, or is "piped" from another process.  Single-

   pass operation has one significant drawback: it is difficult to
   perform encode operations using the Distinguished Encoding Rules
   (DER) [X.509-88] encoding in a single pass since the lengths of the
   various components may not be known in advance.  However, signed
   attributes within the signed-data content type and authenticated
   attributes within the authenticated-data content type need to be
   transmitted in DER form to ensure that recipients can verify a
   content that contains one or more unrecognized attributes.  Signed
   attributes and authenticated attributes are the only data types used
   in the CMS that require DER encoding.

3.  General Syntax

   The following object identifier identifies the content information
   type:

      id-ct-contentInfo OBJECT IDENTIFIER ::= { iso(1) member-body(2)
         us(840) rsadsi(113549) pkcs(1) pkcs9(9) smime(16) ct(1) 6 }

   The CMS associates a content type identifier with a content.  The
   syntax MUST have ASN.1 type ContentInfo:

      ContentInfo ::= SEQUENCE {
        contentType ContentType,
        content [0] EXPLICIT ANY DEFINED BY contentType }

      ContentType ::= OBJECT IDENTIFIER

   The fields of ContentInfo have the following meanings:

      contentType indicates the type of the associated content.  It is
      an object identifier; it is a unique string of integers assigned
      by an authority that defines the content type.

      content is the associated content.  The type of content can be
      determined uniquely by contentType.  Content types for data,
      signed-data, enveloped-data, digested-data, encrypted-data, and
      authenticated-data are defined in this document.  If additional
      content types are defined in other documents, the ASN.1 type
      defined SHOULD NOT be a CHOICE type.

4.  Data Content Type

   The following object identifier identifies the data content type:

      id-data OBJECT IDENTIFIER ::= { iso(1) member-body(2)
         us(840) rsadsi(113549) pkcs(1) pkcs7(7) 1 }

   The data content type is intended to refer to arbitrary octet
   strings, such as ASCII text files; the interpretation is left to the
   application.  Such strings need not have any internal structure
   (although they could have their own ASN.1 definition or other
   structure).

   S/MIME uses id-data to identify MIME encoded content.  The use of
   this content identifier is specified in RFC 2311 for S/MIME v2
   [OLDMSG] and RFC 3851 for S/MIME v3.1 [MSG].

   The data content type is generally encapsulated in the signed-data,
   enveloped-data, digested-data, encrypted-data, or authenticated-data
   content type.

5.  Signed-data Content Type

   The signed-data content type consists of a content of any type and
   zero or more signature values.  Any number of signers in parallel can
   sign any type of content.

   The typical application of the signed-data content type represents
   one signer's digital signature on content of the data content type.
   Another typical application disseminates certificates and certificate
   revocation lists (CRLs).

   The process by which signed-data is constructed involves the
   following steps:

      1. For each signer, a message digest, or hash value, is computed
         on the content with a signer-specific message-digest algorithm.
         If the signer is signing any information other than the
         content, the message digest of the content and the other
         information are digested with the signer's message digest
         algorithm (see Section 5.4), and the result becomes the
         "message digest."

      2. For each signer, the message digest is digitally signed using
         the signer's private key.

      3. For each signer, the signature value and other signer-specific
         information are collected into a SignerInfo value, as defined
         in Section 5.3.  Certificates and CRLs for each signer, and
         those not corresponding to any signer, are collected in this
         step.

      4. The message digest algorithms for all the signers and the
         SignerInfo values for all the signers are collected together
         with the content into a SignedData value, as defined in Section
         5.1.

   A recipient independently computes the message digest.  This message
   digest and the signer's public key are used to verify the signature
   value.  The signer's public key is referenced either by an issuer
   distinguished name along with an issuer-specific serial number or by
   a subject key identifier that uniquely identifies the certificate
   containing the public key.  The signer's certificate can be included
   in the SignedData certificates field.

   This section is divided into six parts.  The first part describes the
   top-level type SignedData, the second part describes
   EncapsulatedContentInfo, the third part describes the per-signer
   information type SignerInfo, and the fourth, fifth, and sixth parts
   describe the message digest calculation, signature generation, and
   signature verification processes, respectively.

5.1.  SignedData Type

   The following object identifier identifies the signed-data content
   type:

      id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
         us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }

   The signed-data content type shall have ASN.1 type SignedData:

      SignedData ::= SEQUENCE {
        version CMSVersion,
        digestAlgorithms DigestAlgorithmIdentifiers,
        encapContentInfo EncapsulatedContentInfo,
        certificates [0] IMPLICIT CertificateSet OPTIONAL,
        crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,
        signerInfos SignerInfos }

      DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier

      SignerInfos ::= SET OF SignerInfo

   The fields of type SignedData have the following meanings:

      version is the syntax version number.  The appropriate value
      depends on certificates, eContentType, and SignerInfo.  The
      version MUST be assigned as follows:

         IF ((certificates is present) AND
            (any certificates with a type of other are present)) OR
            ((crls is present) AND
            (any crls with a type of other are present))
         THEN version MUST be 5
         ELSE
            IF (certificates is present) AND
               (any version 2 attribute certificates are present)
            THEN version MUST be 4
            ELSE
               IF ((certificates is present) AND
                  (any version 1 attribute certificates are present)) OR
                  (any SignerInfo structures are version 3) OR
                  (encapContentInfo eContentType is other than id-data)
               THEN version MUST be 3
               ELSE version MUST be 1

      digestAlgorithms is a collection of message digest algorithm
      identifiers.  There MAY be any number of elements in the
      collection, including zero.  Each element identifies the message
      digest algorithm, along with any associated parameters, used by
      one or more signer.  The collection is intended to list the
      message digest algorithms employed by all of the signers, in any
      order, to facilitate one-pass signature verification.
      Implementations MAY fail to validate signatures that use a digest
      algorithm that is not included in this set.  The message digesting
      process is described in Section 5.4.

      encapContentInfo is the signed content, consisting of a content
      type identifier and the content itself.  Details of the
      EncapsulatedContentInfo type are discussed in section 5.2.

      certificates is a collection of certificates.  It is intended that
      the set of certificates be sufficient to contain certification
      paths from a recognized "root" or "top-level certification
      authority" to all of the signers in the signerInfos field.  There
      may be more certificates than necessary, and there may be
      certificates sufficient to contain certification paths from two or
      more independent top-level certification authorities.  There may
      also be fewer certificates than necessary, if it is expected that
      recipients have an alternate means of obtaining necessary
      certificates (e.g., from a previous set of certificates).  The
      signer's certificate MAY be included.  The use of version 1
      attribute certificates is strongly discouraged.

      crls is a collection of revocation status information.  It is
      intended that the collection contain information sufficient to
      determine whether the certificates in the certificates field are

      valid, but such correspondence is not necessary.  Certificate
      revocation lists (CRLs) are the primary source of revocation
      status information.  There MAY be more CRLs than necessary, and
      there MAY also be fewer CRLs than necessary.
      signerInfos is a collection of per-signer information.  There MAY
      be any number of elements in the collection, including zero.  The
      details of the SignerInfo type are discussed in section 5.3.
      Since each signer can employ a digital signature technique and
      future specifications could update the syntax, all implementations
      MUST gracefully handle unimplemented versions of SignerInfo.
      Further, since all implementations will not support every possible
      signature algorithm, all implementations MUST gracefully handle
      unimplemented signature algorithms when they are encountered.

5.2.  EncapsulatedContentInfo Type

   The content is represented in the type EncapsulatedContentInfo:

      EncapsulatedContentInfo ::= SEQUENCE {
        eContentType ContentType,
        eContent [0] EXPLICIT OCTET STRING OPTIONAL }

      ContentType ::= OBJECT IDENTIFIER

   The fields of type EncapsulatedContentInfo have the following
   meanings:

      eContentType is an object identifier.  The object identifier
      uniquely specifies the content type.

      eContent is the content itself, carried as an octet string.  The
      eContent need not be DER encoded.

   The optional omission of the eContent within the
   EncapsulatedContentInfo field makes it possible to construct
   "external signatures."  In the case of external signatures, the
   content being signed is absent from the EncapsulatedContentInfo value
   included in the signed-data content type.  If the eContent value
   within EncapsulatedContentInfo is absent, then the signatureValue is
   calculated and the eContentType is assigned as though the eContent
   value was present.

   In the degenerate case where there are no signers, the
   EncapsulatedContentInfo value being "signed" is irrelevant.  In this
   case, the content type within the EncapsulatedContentInfo value being
   "signed" MUST be id-data (as defined in section 4), and the content
   field of the EncapsulatedContentInfo value MUST be omitted.

5.2.1.  Compatibility with PKCS #7

   This section contains a word of warning to implementers that wish to
   support both the CMS and PKCS #7 [PKCS#7] SignedData content types.

   Both the CMS and PKCS #7 identify the type of the encapsulated
   content with an object identifier, but the ASN.1 type of the content
   itself is variable in PKCS #7 SignedData content type.

   PKCS #7 defines content as:

      content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL

   The CMS defines eContent as:

      eContent [0] EXPLICIT OCTET STRING OPTIONAL

   The CMS definition is much easier to use in most applications, and it
   is compatible with both S/MIME v2 and S/MIME v3.  S/MIME signed
   messages using the CMS and PKCS #7 are compatible because identical
   signed message formats are specified in RFC 2311 for S/MIME v2
   [OLDMSG] and RFC 3851 for S/MIME v3.1 [MSG].  S/MIME v2 encapsulates
   the MIME content in a Data type (that is, an OCTET STRING) carried in
   the SignedData contentInfo content ANY field, and S/MIME v3 carries
   the MIME content in the SignedData encapContentInfo eContent OCTET
   STRING.  Therefore, in both S/MIME v2 and S/MIME v3, the MIME content
   is placed in an OCTET STRING and the message digest is computed over
   the identical portions of the content.  That is, the message digest
   is computed over the octets comprising the value of the OCTET STRING,
   neither the tag nor length octets are included.

   There are incompatibilities between the CMS and PKCS #7 SignedData
   types when the encapsulated content is not formatted using the Data
   type.  For example, when an RFC 2634 [ESS] signed receipt is
   encapsulated in the CMS SignedData type, then the Receipt SEQUENCE is
   encoded in the SignedData encapContentInfo eContent OCTET STRING and
   the message digest is computed using the entire Receipt SEQUENCE
   encoding (including tag, length and value octets).  However, if an
   RFC 2634 signed receipt is encapsulated in the PKCS #7 SignedData
   type, then the Receipt SEQUENCE is DER encoded [X.509-88] in the
   SignedData contentInfo content ANY field (a SEQUENCE, not an OCTET
   STRING).  Therefore, the message digest is computed using only the
   value octets of the Receipt SEQUENCE encoding.

   The following strategy can be used to achieve backward compatibility
   with PKCS #7 when processing SignedData content types.  If the
   implementation is unable to ASN.1 decode the SignedData type using
   the CMS SignedData encapContentInfo eContent OCTET STRING syntax,

   then the implementation MAY attempt to decode the SignedData type
   using the PKCS #7 SignedData contentInfo content ANY syntax and
   compute the message digest accordingly.

   The following strategy can be used to achieve backward compatibility
   with PKCS #7 when creating a SignedData content type in which the
   encapsulated content is not formatted using the Data type.
   Implementations MAY examine the value of the eContentType, and then
   adjust the expected DER encoding of eContent based on the object
   identifier value.  For example, to support Microsoft Authenticode
   [MSAC], the following information MAY be included:

      eContentType Object Identifier is set to { 1 3 6 1 4 1 311 2 1 4 }

      eContent contains DER encoded Authenticode signing information

5.3.  SignerInfo Type

   Per-signer information is represented in the type SignerInfo:

      SignerInfo ::= SEQUENCE {
        version CMSVersion,
        sid SignerIdentifier,
        digestAlgorithm DigestAlgorithmIdentifier,
        signedAttrs [0] IMPLICIT SignedAttributes OPTIONAL,
        signatureAlgorithm SignatureAlgorithmIdentifier,
        signature SignatureValue,
        unsignedAttrs [1] IMPLICIT UnsignedAttributes OPTIONAL }

      SignerIdentifier ::= CHOICE {
        issuerAndSerialNumber IssuerAndSerialNumber,
        subjectKeyIdentifier [0] SubjectKeyIdentifier }

      SignedAttributes ::= SET SIZE (1..MAX) OF Attribute

      UnsignedAttributes ::= SET SIZE (1..MAX) OF Attribute

      Attribute ::= SEQUENCE {
        attrType OBJECT IDENTIFIER,
        attrValues SET OF AttributeValue }

      AttributeValue ::= ANY

      SignatureValue ::= OCTET STRING

   The fields of type SignerInfo have the following meanings:

      version is the syntax version number.  If the SignerIdentifier is
      the CHOICE issuerAndSerialNumber, then the version MUST be 1.  If
      the SignerIdentifier is subjectKeyIdentifier, then the version
      MUST be 3.

      sid specifies the signer's certificate (and thereby the signer's
      public key).  The signer's public key is needed by the recipient
      to verify the signature.  SignerIdentifier provides two
      alternatives for specifying the signer's public key.  The
      issuerAndSerialNumber alternative identifies the signer's
      certificate by the issuer's distinguished name and the certificate
      serial number; the subjectKeyIdentifier identifies the signer's
      certificate by a key identifier.  When an X.509 certificate is
      reference, the key identifier matches the X.509
      subjectKeyIdentifier extension value.  When other certificate
      formats are referenced, the documents that specify the certificate
      format and their use with the CMS must include details on matching
      the key identifier to the appropriate certificate field.
      Implementations MUST support the reception of the
      issuerAndSerialNumber and subjectKeyIdentifier forms of
      SignerIdentifier.  When generating a SignerIdentifier,
      implementations MAY support one of the forms (either
      issuerAndSerialNumber or subjectKeyIdentifier) and always use it,
      or implementations MAY arbitrarily mix the two forms.  However,
      subjectKeyIdentifier MUST be used to refer to a public key
      contained in a non-X.509 certificate.

      digestAlgorithm identifies the message digest algorithm, and any
      associated parameters, used by the signer.  The message digest is
      computed on either the content being signed or the content
      together with the signed attributes using the process described in
      section 5.4.  The message digest algorithm SHOULD be among those
      listed in the digestAlgorithms field of the associated SignerData.
      Implementations MAY fail to validate signatures that use a digest
      algorithm that is not included in the SignedData digestAlgorithms
      set.

      signedAttrs is a collection of attributes that are signed.  The
      field is optional, but it MUST be present if the content type of
      the EncapsulatedContentInfo value being signed is not id-data.
      SignedAttributes MUST be DER encoded, even if the rest of the
      structure is BER encoded.  Useful attribute types, such as signing
      time, are defined in Section 11.  If the field is present, it MUST
      contain, at a minimum, the following two attributes:

         A content-type attribute having as its value the content type
         of the EncapsulatedContentInfo value being signed.  Section
         11.1 defines the content-type attribute.  However, the
         content-type attribute MUST NOT be used as part of a
         countersignature unsigned attribute as defined in section 11.4.

         A message-digest attribute, having as its value the message
         digest of the content.  Section 11.2 defines the message-digest
         attribute.

      signatureAlgorithm identifies the signature algorithm, and any
      associated parameters, used by the signer to generate the digital
      signature.

      signature is the result of digital signature generation, using the
      message digest and the signer's private key.  The details of the
      signature depend on the signature algorithm employed.

      unsignedAttrs is a collection of attributes that are not signed.
      The field is optional.  Useful attribute types, such as
      countersignatures, are defined in Section 11.

   The fields of type SignedAttribute and UnsignedAttribute have the
   following meanings:

      attrType indicates the type of attribute.  It is an object
      identifier.

      attrValues is a set of values that comprise the attribute.  The
      type of each value in the set can be determined uniquely by
      attrType.  The attrType can impose restrictions on the number of
      items in the set.

5.4.  Message Digest Calculation Process

   The message digest calculation process computes a message digest on
   either the content being signed or the content together with the
   signed attributes.  In either case, the initial input to the message
   digest calculation process is the "value" of the encapsulated content
   being signed.  Specifically, the initial input is the
   encapContentInfo eContent OCTET STRING to which the signing process
   is applied.  Only the octets comprising the value of the eContent
   OCTET STRING are input to the message digest algorithm, not the tag
   or the length octets.

   The result of the message digest calculation process depends on
   whether the signedAttrs field is present.  When the field is absent,
   the result is just the message digest of the content as described

   above.  When the field is present, however, the result is the message
   digest of the complete DER encoding of the SignedAttrs value
   contained in the signedAttrs field.  Since the SignedAttrs value,
   when present, must contain the content-type and the message-digest
   attributes, those values are indirectly included in the result.  The
   content-type attribute MUST NOT be included in a countersignature
   unsigned attribute as defined in section 11.4.  A separate encoding
   of the signedAttrs field is performed for message digest calculation.
   The IMPLICIT [0] tag in the signedAttrs is not used for the DER
   encoding, rather an EXPLICIT SET OF tag is used.  That is, the DER
   encoding of the EXPLICIT SET OF tag, rather than of the IMPLICIT [0]
   tag, MUST be included in the message digest calculation along with
   the length and content octets of the SignedAttributes value.

   When the signedAttrs field is absent, only the octets comprising the
   value of the SignedData encapContentInfo eContent OCTET STRING (e.g.,
   the contents of a file) are input to the message digest calculation.
   This has the advantage that the length of the content being signed
   need not be known in advance of the signature generation process.

   Although the encapContentInfo eContent OCTET STRING tag and length
   octets are not included in the message digest calculation, they are
   protected by other means.  The length octets are protected by the
   nature of the message digest algorithm since it is computationally
   infeasible to find any two distinct message contents of any length
   that have the same message digest.

5.5.  Signature Generation Process

   The input to the signature generation process includes the result of
   the message digest calculation process and the signer's private key.
   The details of the signature generation depend on the signature
   algorithm employed.  The object identifier, along with any
   parameters, that specifies the signature algorithm employed by the
   signer is carried in the signatureAlgorithm field.  The signature
   value generated by the signer MUST be encoded as an OCTET STRING and
   carried in the signature field.

5.6.  Signature Verification Process

   The input to the signature verification process includes the result
   of the message digest calculation process and the signer's public
   key.  The recipient MAY obtain the correct public key for the signer
   by any means, but the preferred method is from a certificate obtained
   from the SignedData certificates field.  The selection and validation
   of the signer's public key MAY be based on certification path

   validation (see [PROFILE]) as well as other external context, but is
   beyond the scope of this document.  The details of the signature
   verification depend on the signature algorithm employed.

   The recipient MUST NOT rely on any message digest values computed by
   the originator.  If the SignedData signerInfo includes
   signedAttributes, then the content message digest MUST be calculated
   as described in section 5.4.  For the signature to be valid, the
   message digest value calculated by the recipient MUST be the same as
   the value of the messageDigest attribute included in the
   signedAttributes of the SignedData signerInfo.

   If the SignedData signerInfo includes signedAttributes, then the
   content-type attribute value MUST match the SignedData
   encapContentInfo eContentType value.

6.  Enveloped-data Content Type

   The enveloped-data content type consists of an encrypted content of
   any type and encrypted content-encryption keys for one or more
   recipients.  The combination of the encrypted content and one
   encrypted content-encryption key for a recipient is a "digital
   envelope" for that recipient.  Any type of content can be enveloped
   for an arbitrary number of recipients using any of the supported key
   management techniques for each recipient.

   The typical application of the enveloped-data content type will
   represent one or more recipients' digital envelopes on content of the
   data or signed-data content types.

   Enveloped-data is constructed by the following steps:

      1. A content-encryption key for a particular content-encryption
         algorithm is generated at random.

      2. The content-encryption key is encrypted for each recipient.
         The details of this encryption depend on the key management
         algorithm used, but four general techniques are supported:

         key transport:  the content-encryption key is encrypted in the
         recipient's public key;

         key agreement:  the recipient's public key and the sender's
         private key are used to generate a pairwise symmetric key, then
         the content-encryption key is encrypted in the pairwise
         symmetric key;

         symmetric key-encryption keys:  the content-encryption key is
         encrypted in a previously distributed symmetric key-encryption
         key; and

         passwords: the content-encryption key is encrypted in a key-
         encryption key that is derived from a password or other shared
         secret value.

      3. For each recipient, the encrypted content-encryption key and
         other recipient-specific information are collected into a
         RecipientInfo value, defined in Section 6.2.

      4. The content is encrypted with the content-encryption key.
         Content encryption may require that the content be padded to a
         multiple of some block size; see Section 6.3.

      5. The RecipientInfo values for all the recipients are collected
         together with the encrypted content to form an EnvelopedData
         value as defined in Section 6.1.

      A recipient opens the digital envelope by decrypting one of the
      encrypted content-encryption keys and then decrypting the
      encrypted content with the recovered content-encryption key.

      This section is divided into four parts.  The first part describes
      the top-level type EnvelopedData, the second part describes the
      per-recipient information type RecipientInfo, and the third and
      fourth parts describe the content-encryption and key-encryption
      processes.

6.1.  EnvelopedData Type

   The following object identifier identifies the enveloped-data content
   type:

      id-envelopedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
          us(840) rsadsi(113549) pkcs(1) pkcs7(7) 3 }

   The enveloped-data content type shall have ASN.1 type EnvelopedData:

    EnvelopedData ::= SEQUENCE {
     version CMSVersion,
     originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
     recipientInfos RecipientInfos,
     encryptedContentInfo EncryptedContentInfo,
     unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }

    OriginatorInfo ::= SEQUENCE {
     certs [0] IMPLICIT CertificateSet OPTIONAL,
     crls [1] IMPLICIT RevocationInfoChoices OPTIONAL }

    RecipientInfos ::= SET SIZE (1..MAX) OF RecipientInfo

    EncryptedContentInfo ::= SEQUENCE {
     contentType ContentType,
     contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
     encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL }

    EncryptedContent ::= OCTET STRING

    UnprotectedAttributes ::= SET SIZE (1..MAX) OF Attribute

   The fields of type EnvelopedData have the following meanings:

      version is the syntax version number.  The appropriate value
      depends on originatorInfo, RecipientInfo, and unprotectedAttrs.
      The version MUST be assigned as follows:

         IF (originatorInfo is present) AND
            ((any certificates with a type of other are present) OR
            (any crls with a type of other are present))
         THEN version is 4
         ELSE
            IF ((originatorInfo is present) AND
               (any version 2 attribute certificates are present)) OR
               (any RecipientInfo structures include pwri) OR
               (any RecipientInfo structures include ori)
            THEN version is 3
            ELSE
               IF (originatorInfo is absent) OR
                  (unprotectedAttrs is absent) OR
                  (all RecipientInfo structures are version 0)
               THEN version is 0
               ELSE version is 2

      originatorInfo optionally provides information about the
      originator.  It is present only if required by the key management
      algorithm.  It may contain certificates and CRLs:

         certs is a collection of certificates.  certs may contain
         originator certificates associated with several different key
         management algorithms.  certs may also contain attribute
         certificates associated with the originator.  The certificates
         contained in certs are intended to be sufficient for all
         recipients to build certification paths from a recognized

         "root" or "top-level certification authority."  However, certs
         may contain more certificates than necessary, and there may be
         certificates sufficient to make certification paths from two or
         more independent top-level certification authorities.
         Alternatively, certs may contain fewer certificates than
         necessary, if it is expected that recipients have an alternate
         means of obtaining necessary certificates (e.g., from a
         previous set of certificates).

         crls is a collection of CRLs.  It is intended that the set
         contain information sufficient to determine whether or not the
         certificates in the certs field are valid, but such
         correspondence is not necessary.  There MAY be more CRLs than
         necessary, and there MAY also be fewer CRLs than necessary.

      recipientInfos is a collection of per-recipient information.
      There MUST be at least one element in the collection.

      encryptedContentInfo is the encrypted content information.

      unprotectedAttrs is a collection of attributes that are not
      encrypted.  The field is optional.  Useful attribute types are
      defined in Section 11.

   The fields of type EncryptedContentInfo have the following meanings:

      contentType indicates the type of content.

      contentEncryptionAlgorithm identifies the content-encryption
      algorithm, and any associated parameters, used to encrypt the
      content.  The content-encryption process is described in Section
      6.3.  The same content-encryption algorithm and content-encryption
      key are used for all recipients.

      encryptedContent is the result of encrypting the content.  The
      field is optional, and if the field is not present, its intended
      value must be supplied by other means.

   The recipientInfos field comes before the encryptedContentInfo field
   so that an EnvelopedData value may be processed in a single pass.

6.2.  RecipientInfo Type

   Per-recipient information is represented in the type RecipientInfo.
   RecipientInfo has a different format for each of the supported key
   management techniques.  Any of the key management techniques can be

   used for each recipient of the same encrypted content.  In all cases,
   the encrypted content-encryption key is transferred to one or more
   recipients.

   Since all implementations will not support every possible key
   management algorithm, all implementations MUST gracefully handle
   unimplemented algorithms when they are encountered.  For example, if
   a recipient receives a content-encryption key encrypted in their RSA
   public key using RSA-OAEP and the implementation only supports RSA
   PKCS #1 v1.5, then a graceful failure must be implemented.

   Implementations MUST support key transport, key agreement, and
   previously distributed symmetric key-encryption keys, as represented
   by ktri, kari, and kekri, respectively.  Implementations MAY support
   the password-based key management as represented by pwri.
   Implementations MAY support any other key management technique as
   represented by ori.  Since each recipient can employ a different key
   management technique and future specifications could define
   additional key management techniques, all implementations MUST
   gracefully handle unimplemented alternatives within the RecipientInfo
   CHOICE, all implementations MUST gracefully handle unimplemented
   versions of otherwise supported alternatives within the RecipientInfo
   CHOICE, and all implementations MUST gracefully handle unimplemented
   or unknown ori alternatives.

            RecipientInfo ::= CHOICE {
              ktri KeyTransRecipientInfo,
              kari [1] KeyAgreeRecipientInfo,
              kekri [2] KEKRecipientInfo,
              pwri [3] PasswordRecipientinfo,
              ori [4] OtherRecipientInfo }

            EncryptedKey ::= OCTET STRING

6.2.1.  KeyTransRecipientInfo Type

   Per-recipient information using key transport is represented in the
   type KeyTransRecipientInfo.  Each instance of KeyTransRecipientInfo
   transfers the content-encryption key to one recipient.

      KeyTransRecipientInfo ::= SEQUENCE {
        version CMSVersion,  -- always set to 0 or 2
        rid RecipientIdentifier,
        keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
        encryptedKey EncryptedKey }

      RecipientIdentifier ::= CHOICE {
        issuerAndSerialNumber IssuerAndSerialNumber,
        subjectKeyIdentifier [0] SubjectKeyIdentifier }

   The fields of type KeyTransRecipientInfo have the following meanings:

      version is the syntax version number.  If the RecipientIdentifier
      is the CHOICE issuerAndSerialNumber, then the version MUST be 0.
      If the RecipientIdentifier is subjectKeyIdentifier, then the
      version MUST be 2.

      rid specifies the recipient's certificate or key that was used by
      the sender to protect the content-encryption key.  The content-
      encryption key is encrypted with the recipient's public key.  The
      RecipientIdentifier provides two alternatives for specifying the
      recipient's certificate, and thereby the recipient's public key.
      The recipient's certificate must contain a key transport public
      key.  Therefore, a recipient X.509 version 3 certificate that
      contains a key usage extension MUST assert the keyEncipherment
      bit.  The issuerAndSerialNumber alternative identifies the
      recipient's certificate by the issuer's distinguished name and the
      certificate serial number; the subjectKeyIdentifier identifies the
      recipient's certificate by a key identifier.  When an X.509
      certificate is referenced, the key identifier matches the X.509
      subjectKeyIdentifier extension value.  When other certificate
      formats are referenced, the documents that specify the certificate
      format and their use with the CMS must include details on matching
      the key identifier to the appropriate certificate field.  For
      recipient processing, implementations MUST support both of these
      alternatives for specifying the recipient's certificate.  For
      sender processing, implementations MUST support at least one of
      these alternatives.

      keyEncryptionAlgorithm identifies the key-encryption algorithm,
      and any associated parameters, used to encrypt the content-
      encryption key for the recipient.  The key-encryption process is
      described in Section 6.4.

      encryptedKey is the result of encrypting the content-encryption
      key for the recipient.

6.2.2.  KeyAgreeRecipientInfo Type

   Recipient information using key agreement is represented in the type
   KeyAgreeRecipientInfo.  Each instance of KeyAgreeRecipientInfo will
   transfer the content-encryption key to one or more recipients that
   use the same key agreement algorithm and domain parameters for that
   algorithm.

      KeyAgreeRecipientInfo ::= SEQUENCE {
        version CMSVersion,  -- always set to 3
        originator [0] EXPLICIT OriginatorIdentifierOrKey,
        ukm [1] EXPLICIT UserKeyingMaterial OPTIONAL,
        keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
        recipientEncryptedKeys RecipientEncryptedKeys }

      OriginatorIdentifierOrKey ::= CHOICE {
        issuerAndSerialNumber IssuerAndSerialNumber,
        subjectKeyIdentifier [0] SubjectKeyIdentifier,
        originatorKey [1] OriginatorPublicKey }

      OriginatorPublicKey ::= SEQUENCE {
        algorithm AlgorithmIdentifier,
        publicKey BIT STRING }

      RecipientEncryptedKeys ::= SEQUENCE OF RecipientEncryptedKey

      RecipientEncryptedKey ::= SEQUENCE {
        rid KeyAgreeRecipientIdentifier,
        encryptedKey EncryptedKey }

      KeyAgreeRecipientIdentifier ::= CHOICE {
        issuerAndSerialNumber IssuerAndSerialNumber,
        rKeyId [0] IMPLICIT RecipientKeyIdentifier }

      RecipientKeyIdentifier ::= SEQUENCE {
        subjectKeyIdentifier SubjectKeyIdentifier,
        date GeneralizedTime OPTIONAL,
        other OtherKeyAttribute OPTIONAL }

      SubjectKeyIdentifier ::= OCTET STRING

   The fields of type KeyAgreeRecipientInfo have the following meanings:

      version is the syntax version number.  It MUST always be 3.

      originator is a CHOICE with three alternatives specifying the
      sender's key agreement public key.  The sender uses the
      corresponding private key and the recipient's public key to
      generate a pairwise key.  The content-encryption key is encrypted
      in the pairwise key.  The issuerAndSerialNumber alternative
      identifies the sender's certificate, and thereby the sender's
      public key, by the issuer's distinguished name and the certificate
      serial number.  The subjectKeyIdentifier alternative identifies
      the sender's certificate, and thereby the sender's public key, by
      a key identifier.  When an X.509 certificate is referenced, the
      key identifier matches the X.509 subjectKeyIdentifier extension

      value.  When other certificate formats are referenced, the
      documents that specify the certificate format and their use with
      the CMS must include details on matching the key identifier to the
      appropriate certificate field.  The originatorKey alternative
      includes the algorithm identifier and sender's key agreement
      public key.  This alternative permits originator anonymity since
      the public key is not certified.  Implementations MUST support all
      three alternatives for specifying the sender's public key.

      ukm is optional.  With some key agreement algorithms, the sender
      provides a User Keying Material (UKM) to ensure that a different
      key is generated each time the same two parties generate a
      pairwise key.  Implementations MUST accept a KeyAgreeRecipientInfo
      SEQUENCE that includes a ukm field.  Implementations that do not
      support key agreement algorithms that make use of UKMs MUST
      gracefully handle the presence of UKMs.

      keyEncryptionAlgorithm identifies the key-encryption algorithm,
      and any associated parameters, used to encrypt the content-
      encryption key with the key-encryption key.  The key-encryption
      process is described in Section 6.4.

      recipientEncryptedKeys includes a recipient identifier and
      encrypted key for one or more recipients.  The
      KeyAgreeRecipientIdentifier is a CHOICE with two alternatives
      specifying the recipient's certificate, and thereby the
      recipient's public key, that was used by the sender to generate a
      pairwise key-encryption key.  The recipient's certificate must
      contain a key agreement public key.  Therefore, a recipient X.509
      version 3 certificate that contains a key usage extension MUST
      assert the keyAgreement bit.  The content-encryption key is
      encrypted in the pairwise key-encryption key.  The
      issuerAndSerialNumber alternative identifies the recipient's
      certificate by the issuer's distinguished name and the certificate
      serial number; the RecipientKeyIdentifier is described below.  The
      encryptedKey is the result of encrypting the content-encryption
      key in the pairwise key-encryption key generated using the key
      agreement algorithm.  Implementations MUST support both
      alternatives for specifying the recipient's certificate.

   The fields of type RecipientKeyIdentifier have the following
   meanings:

      subjectKeyIdentifier identifies the recipient's certificate by a
      key identifier.  When an X.509 certificate is referenced, the key
      identifier matches the X.509 subjectKeyIdentifier extension value.
      When other certificate formats are referenced, the documents that

      specify the certificate format and their use with the CMS must
      include details on matching the key identifier to the appropriate
      certificate field.

      date is optional.  When present, the date specifies which of the
      recipient's previously distributed UKMs was used by the sender.

      other is optional.  When present, this field contains additional
      information used by the recipient to locate the public keying
      material used by the sender.

6.2.3.  KEKRecipientInfo Type

   Recipient information using previously distributed symmetric keys is
   represented in the type KEKRecipientInfo.  Each instance of
   KEKRecipientInfo will transfer the content-encryption key to one or
   more recipients who have the previously distributed key-encryption
   key.

      KEKRecipientInfo ::= SEQUENCE {
        version CMSVersion,  -- always set to 4
        kekid KEKIdentifier,
        keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
        encryptedKey EncryptedKey }

      KEKIdentifier ::= SEQUENCE {
        keyIdentifier OCTET STRING,
        date GeneralizedTime OPTIONAL,
        other OtherKeyAttribute OPTIONAL }

   The fields of type KEKRecipientInfo have the following meanings:

      version is the syntax version number.  It MUST always be 4.

      kekid specifies a symmetric key-encryption key that was previously
      distributed to the sender and one or more recipients.

      keyEncryptionAlgorithm identifies the key-encryption algorithm,
      and any associated parameters, used to encrypt the content-
      encryption key with the key-encryption key.  The key-encryption
      process is described in Section 6.4.

      encryptedKey is the result of encrypting the content-encryption
      key in the key-encryption key.

   The fields of type KEKIdentifier have the following meanings:

      keyIdentifier identifies the key-encryption key that was
      previously distributed to the sender and one or more recipients.

      date is optional.  When present, the date specifies a single key-
      encryption key from a set that was previously distributed.

      other is optional.  When present, this field contains additional
      information used by the recipient to determine the key-encryption
      key used by the sender.

6.2.4.  PasswordRecipientInfo Type

   Recipient information using a password or shared secret value is
   represented in the type PasswordRecipientInfo.  Each instance of
   PasswordRecipientInfo will transfer the content-encryption key to one
   or more recipients who possess the password or shared secret value.

   The PasswordRecipientInfo Type is specified in RFC 3211 [PWRI].  The
   PasswordRecipientInfo structure is repeated here for completeness.

      PasswordRecipientInfo ::= SEQUENCE {
        version CMSVersion,   -- Always set to 0
        keyDerivationAlgorithm [0] KeyDerivationAlgorithmIdentifier
                                     OPTIONAL,
        keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
        encryptedKey EncryptedKey }

   The fields of type PasswordRecipientInfo have the following meanings:

      version is the syntax version number.  It MUST always be 0.

      keyDerivationAlgorithm identifies the key-derivation algorithm,
      and any associated parameters, used to derive the key-encryption
      key from the password or shared secret value.  If this field is
      absent, the key-encryption key is supplied from an external
      source, for example a hardware crypto token such as a smart card.

      keyEncryptionAlgorithm identifies the encryption algorithm, and
      any associated parameters, used to encrypt the content-encryption
      key with the key-encryption key.

      encryptedKey is the result of encrypting the content-encryption
      key with the key-encryption key.

6.2.5.  OtherRecipientInfo Type

   Recipient information for additional key management techniques are
   represented in the type OtherRecipientInfo.  The OtherRecipientInfo
   type allows key management techniques beyond key transport, key
   agreement, previously distributed symmetric key-encryption keys, and
   password-based key management to be specified in future documents.
   An object identifier uniquely identifies such key management
   techniques.

      OtherRecipientInfo ::= SEQUENCE {
        oriType OBJECT IDENTIFIER,
        oriValue ANY DEFINED BY oriType }

   The fields of type OtherRecipientInfo have the following meanings:

      oriType identifies the key management technique.

      oriValue contains the protocol data elements needed by a recipient
      using the identified key management technique.

6.3.  Content-encryption Process

   The content-encryption key for the desired content-encryption
   algorithm is randomly generated.  The data to be protected is padded
   as described below, then the padded data is encrypted using the
   content-encryption key.  The encryption operation maps an arbitrary
   string of octets (the data) to another string of octets (the
   ciphertext) under control of a content-encryption key.  The encrypted
   data is included in the EnvelopedData encryptedContentInfo
   encryptedContent OCTET STRING.

   Some content-encryption algorithms assume the input length is a
   multiple of k octets, where k is greater than one.  For such
   algorithms, the input shall be padded at the trailing end with k-(lth
   mod k) octets all having value k-(lth mod k), where lth is the length
   of the input.  In other words, the input is padded at the trailing
   end with one of the following strings:

                     01 -- if lth mod k = k-1
                  02 02 -- if lth mod k = k-2
                      .
                      .
                      .
            k k ... k k -- if lth mod k = 0

   The padding can be removed unambiguously since all input is padded,
   including input values that are already a multiple of the block size,
   and no padding string is a suffix of another.  This padding method is
   well defined if and only if k is less than 256.

6.4.  Key-encryption Process

   The input to the key-encryption process -- the value supplied to the
   recipient's key-encryption algorithm -- is just the "value" of the
   content-encryption key.

   Any of the aforementioned key management techniques can be used for
   each recipient of the same encrypted content.

7.  Digested-data Content Type

   The digested-data content type consists of content of any type and a
   message digest of the content.

   Typically, the digested-data content type is used to provide content
   integrity, and the result generally becomes an input to the
   enveloped-data content type.

   The following steps construct digested-data:

      1. A message digest is computed on the content with a message-
         digest algorithm.

      2. The message-digest algorithm and the message digest are
         collected together with the content into a DigestedData value.

   A recipient verifies the message digest by comparing the message
   digest to an independently computed message digest.

   The following object identifier identifies the digested-data content
   type:

      id-digestedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
          us(840) rsadsi(113549) pkcs(1) pkcs7(7) 5 }

   The digested-data content type shall have ASN.1 type DigestedData:

      DigestedData ::= SEQUENCE {
        version CMSVersion,
        digestAlgorithm DigestAlgorithmIdentifier,
        encapContentInfo EncapsulatedContentInfo,
        digest Digest }

      Digest ::= OCTET STRING

   The fields of type DigestedData have the following meanings:

      version is the syntax version number.  If the encapsulated content
      type is id-data, then the value of version MUST be 0; however, if
      the encapsulated content type is other than id-data, then the
      value of version MUST be 2.

      digestAlgorithm identifies the message digest algorithm, and any
      associated parameters, under which the content is digested.  The
      message-digesting process is the same as in Section 5.4 in the
      case when there are no signed attributes.

      encapContentInfo is the content that is digested, as defined in
      section 5.2.

      digest is the result of the message-digesting process.

   The ordering of the digestAlgorithm field, the encapContentInfo
   field, and the digest field makes it possible to process a
   DigestedData value in a single pass.

8.  Encrypted-data Content Type

   The encrypted-data content type consists of encrypted content of any
   type.  Unlike the enveloped-data content type, the encrypted-data
   content type has neither recipients nor encrypted content-encryption
   keys.  Keys MUST be managed by other means.

   The typical application of the encrypted-data content type will be to
   encrypt the content of the data content type for local storage,
   perhaps where the encryption key is derived from a password.

   The following object identifier identifies the encrypted-data content
   type:

      id-encryptedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
          us(840) rsadsi(113549) pkcs(1) pkcs7(7) 6 }

   The encrypted-data content type shall have ASN.1 type EncryptedData:

      EncryptedData ::= SEQUENCE {
        version CMSVersion,
        encryptedContentInfo EncryptedContentInfo,
        unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }

   The fields of type EncryptedData have the following meanings:

      version is the syntax version number.  If unprotectedAttrs is
      present, then version MUST be 2.  If unprotectedAttrs is absent,
      then version MUST be 0.

      encryptedContentInfo is the encrypted content information, as
      defined in Section 6.1.

      unprotectedAttrs is a collection of attributes that are not
      encrypted.  The field is optional.  Useful attribute types are
      defined in Section 11.

9.  Authenticated-data Content Type

   The authenticated-data content type consists of content of any type,
   a message authentication code (MAC), and encrypted authentication
   keys for one or more recipients.  The combination of the MAC and one
   encrypted authentication key for a recipient is necessary for that
   recipient to verify the integrity of the content.  Any type of
   content can be integrity protected for an arbitrary number of
   recipients.

   The process by which authenticated-data is constructed involves the
   following steps:

      1. A message-authentication key for a particular message-
         authentication algorithm is generated at random.

      2. The message-authentication key is encrypted for each recipient.
         The details of this encryption depend on the key management
         algorithm used.

      3. For each recipient, the encrypted message-authentication key
         and other recipient-specific information are collected into a
         RecipientInfo value, defined in Section 6.2.

      4. Using the message-authentication key, the originator computes a
         MAC value on the content.  If the originator is authenticating
         any information in addition to the content (see Section 9.2), a
         message digest is calculated on the content, the message digest

         of the content and the other information are authenticated
         using the message-authentication key, and the result becomes
         the "MAC value."

9.1.  AuthenticatedData Type

   The following object identifier identifies the authenticated-data
   content type:

      id-ct-authData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
         us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16)
         ct(1) 2 }

   The authenticated-data content type shall have ASN.1 type
   AuthenticatedData:

      AuthenticatedData ::= SEQUENCE {
        version CMSVersion,
        originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
        recipientInfos RecipientInfos,
        macAlgorithm MessageAuthenticationCodeAlgorithm,
        digestAlgorithm [1] DigestAlgorithmIdentifier OPTIONAL,
        encapContentInfo EncapsulatedContentInfo,
        authAttrs [2] IMPLICIT AuthAttributes OPTIONAL,
        mac MessageAuthenticationCode,
        unauthAttrs [3] IMPLICIT UnauthAttributes OPTIONAL }

      AuthAttributes ::= SET SIZE (1..MAX) OF Attribute

      UnauthAttributes ::= SET SIZE (1..MAX) OF Attribute

      MessageAuthenticationCode ::= OCTET STRING

   The fields of type AuthenticatedData have the following meanings:

      version is the syntax version number.  The version MUST be
      assigned as follows:

         IF (originatorInfo is present) AND
            ((any certificates with a type of other are present) OR
            (any crls with a type of other are present))
         THEN version is 3
         ELSE
            IF ((originatorInfo is present) AND
               (any version 2 attribute certificates are present))
            THEN version is 1
            ELSE version is 0

      originatorInfo optionally provides information about the
      originator.  It is present only if required by the key management
      algorithm.  It MAY contain certificates, attribute certificates,
      and CRLs, as defined in Section 6.1.

      recipientInfos is a collection of per-recipient information, as
      defined in Section 6.1.  There MUST be at least one element in the
      collection.

      macAlgorithm is a message authentication code (MAC) algorithm
      identifier.  It identifies the MAC algorithm, along with any
      associated parameters, used by the originator.  Placement of the
      macAlgorithm field facilitates one-pass processing by the
      recipient.

      digestAlgorithm identifies the message digest algorithm, and any
      associated parameters, used to compute a message digest on the
      encapsulated content if authenticated attributes are present.  The
      message digesting process is described in Section 9.2.  Placement
      of the digestAlgorithm field facilitates one-pass processing by
      the recipient.  If the digestAlgorithm field is present, then the
      authAttrs field MUST also be present.

      encapContentInfo is the content that is authenticated, as defined
      in section 5.2.

      authAttrs is a collection of authenticated attributes.  The
      authAttrs structure is optional, but it MUST be present if the
      content type of the EncapsulatedContentInfo value being
      authenticated is not id-data.  If the authAttrs field is present,
      then the digestAlgorithm field MUST also be present.  The
      AuthAttributes structure MUST be DER encoded, even if the rest of
      the structure is BER encoded.  Useful attribute types are defined
      in Section 11.  If the authAttrs field is present, it MUST
      contain, at a minimum, the following two attributes:

         A content-type attribute having as its value the content type
         of the EncapsulatedContentInfo value being authenticated.
         Section 11.1 defines the content-type attribute.

         A message-digest attribute, having as its value the message
         digest of the content.  Section 11.2 defines the message-digest
         attribute.

      mac is the message authentication code.

      unauthAttrs is a collection of attributes that are not
      authenticated.  The field is optional.  To date, no attributes
      have been defined for use as unauthenticated attributes, but other
      useful attribute types are defined in Section 11.

9.2.  MAC Generation

   The MAC calculation process computes a message authentication code
   (MAC) on either the content being authenticated or a message digest
   of content being authenticated together with the originator's
   authenticated attributes.

   If authAttrs field is absent, the input to the MAC calculation
   process is the value of the encapContentInfo eContent OCTET STRING.
   Only the octets comprising the value of the eContent OCTET STRING are
   input to the MAC algorithm; the tag and the length octets are
   omitted.  This has the advantage that the length of the content being
   authenticated need not be known in advance of the MAC generation
   process.

   If authAttrs field is present, the content-type attribute (as
   described in Section 11.1) and the message-digest attribute (as
   described in section 11.2) MUST be included, and the input to the MAC
   calculation process is the DER encoding of authAttrs.  A separate
   encoding of the authAttrs field is performed for message digest
   calculation.  The IMPLICIT [2] tag in the authAttrs field is not used
   for the DER encoding, rather an EXPLICIT SET OF tag is used.  That
   is, the DER encoding of the SET OF tag, rather than of the IMPLICIT
   [2] tag, is to be included in the message digest calculation along
   with the length and content octets of the authAttrs value.

   The message digest calculation process computes a message digest on
   the content being authenticated.  The initial input to the message
   digest calculation process is the "value" of the encapsulated content
   being authenticated.  Specifically, the input is the encapContentInfo
   eContent OCTET STRING to which the authentication process is applied.
   Only the octets comprising the value of the encapContentInfo eContent
   OCTET STRING are input to the message digest algorithm, not the tag
   or the length octets.  This has the advantage that the length of the
   content being authenticated need not be known in advance.  Although
   the encapContentInfo eContent OCTET STRING tag and length octets are
   not included in the message digest calculation, they are still
   protected by other means.  The length octets are protected by the
   nature of the message digest algorithm since it is computationally
   infeasible to find any two distinct contents of any length that have
   the same message digest.

   The input to the MAC calculation process includes the MAC input data,
   defined above, and an authentication key conveyed in a recipientInfo
   structure.  The details of MAC calculation depend on the MAC
   algorithm employed (e.g., HMAC).  The object identifier, along with
   any parameters, that specifies the MAC algorithm employed by the
   originator is carried in the macAlgorithm field.  The MAC value
   generated by the originator is encoded as an OCTET STRING and carried
   in the mac field.

9.3.  MAC Verification

   The input to the MAC verification process includes the input data
   (determined based on the presence or absence of the authAttrs field,
   as defined in 9.2), and the authentication key conveyed in
   recipientInfo.  The details of the MAC verification process depend on
   the MAC algorithm employed.

   The recipient MUST NOT rely on any MAC values or message digest
   values computed by the originator.  The content is authenticated as
   described in section 9.2.  If the originator includes authenticated
   attributes, then the content of the authAttrs is authenticated as
   described in section 9.2.  For authentication to succeed, the MAC
   value calculated by the recipient MUST be the same as the value of
   the mac field.  Similarly, for authentication to succeed when the
   authAttrs field is present, the content message digest value
   calculated by the recipient MUST be the same as the message digest
   value included in the authAttrs message-digest attribute.

   If the AuthenticatedData includes authAttrs, then the content-type
   attribute value MUST match the AuthenticatedData encapContentInfo
   eContentType value.

10.  Useful Types

   This section is divided into two parts.  The first part defines
   algorithm identifiers, and the second part defines other useful
   types.

10.1.  Algorithm Identifier Types

   All of the algorithm identifiers have the same type:

   AlgorithmIdentifier.  The definition of AlgorithmIdentifier is taken
   from X.509 [X.509-88].

   There are many alternatives for each algorithm type.

10.1.1.  DigestAlgorithmIdentifier

   The DigestAlgorithmIdentifier type identifies a message-digest
   algorithm.  Examples include SHA-1, MD2, and MD5.  A message-digest
   algorithm maps an octet string (the content) to another octet string
   (the message digest).

      DigestAlgorithmIdentifier ::= AlgorithmIdentifier

10.1.2.  SignatureAlgorithmIdentifier

   The SignatureAlgorithmIdentifier type identifies a signature
   algorithm.  Examples include RSA, DSA, and ECDSA.  A signature
   algorithm supports signature generation and verification operations.
   The signature generation operation uses the message digest and the
   signer's private key to generate a signature value.  The signature
   verification operation uses the message digest and the signer's
   public key to determine whether or not a signature value is valid.
   Context determines which operation is intended.

      SignatureAlgorithmIdentifier ::= AlgorithmIdentifier

10.1.3.  KeyEncryptionAlgorithmIdentifier

   The KeyEncryptionAlgorithmIdentifier type identifies a key-encryption
   algorithm used to encrypt a content-encryption key.  The encryption
   operation maps an octet string (the key) to another octet string (the
   encrypted key) under control of a key-encryption key.  The decryption
   operation is the inverse of the encryption operation.  Context
   determines which operation is intended.

   The details of encryption and decryption depend on the key management
   algorithm used.  Key transport, key agreement, previously distributed
   symmetric key-encrypting keys, and symmetric key-encrypting keys
   derived from passwords are supported.

      KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier

10.1.4.  ContentEncryptionAlgorithmIdentifier

   The ContentEncryptionAlgorithmIdentifier type identifies a content-
   encryption algorithm.  Examples include Triple-DES and RC2.  A
   content-encryption algorithm supports encryption and decryption
   operations.  The encryption operation maps an octet string (the
   plaintext) to another octet string (the ciphertext) under control of

   a content-encryption key.  The decryption operation is the inverse of
   the encryption operation.  Context determines which operation is
   intended.

      ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier

10.1.5.  MessageAuthenticationCodeAlgorithm

   The MessageAuthenticationCodeAlgorithm type identifies a message
   authentication code (MAC) algorithm.  Examples include DES-MAC and
   HMAC-SHA-1.  A MAC algorithm supports generation and verification
   operations.  The MAC generation and verification operations use the
   same symmetric key.  Context determines which operation is intended.

      MessageAuthenticationCodeAlgorithm ::= AlgorithmIdentifier

10.1.6.  KeyDerivationAlgorithmIdentifier

   The KeyDerivationAlgorithmIdentifier type is specified in RFC 3211
   [PWRI].  The KeyDerivationAlgorithmIdentifier definition is repeated
   here for completeness.

   Key derivation algorithms convert a password or shared secret value
   into a key-encryption key.

      KeyDerivationAlgorithmIdentifier ::= AlgorithmIdentifier

10.2.  Other Useful Types

   This section defines types that are used other places in the
   document.  The types are not listed in any particular order.

10.2.1.  RevocationInfoChoices

   The RevocationInfoChoices type gives a set of revocation status
   information alternatives.  It is intended that the set contain
   information sufficient to determine whether the certificates and
   attribute certificates with which the set is associated are revoked.
   However, there MAY be more revocation status information than
   necessary or there MAY be less revocation status information than
   necessary.  X.509 Certificate revocation lists (CRLs) [X.509-97] are
   the primary source of revocation status information, but any other
   revocation information format can be supported.  The
   OtherRevocationInfoFormat alternative is provided to support any
   other revocation information format without further modifications to
   the CMS.  For example, Online Certificate Status Protocol (OCSP)
   Responses [OCSP] can be supported using the
   OtherRevocationInfoFormat.

   The CertificateList may contain a CRL, an Authority Revocation List
   (ARL), a Delta CRL, or an Attribute Certificate Revocation List.  All
   of these lists share a common syntax.

   The CertificateList type gives a certificate revocation list (CRL).
   CRLs are specified in X.509 [X.509-97], and they are profiled for use
   in the Internet in RFC 3280 [PROFILE].

   The definition of CertificateList is taken from X.509.

      RevocationInfoChoices ::= SET OF RevocationInfoChoice

      RevocationInfoChoice ::= CHOICE {
        crl CertificateList,
        other [1] IMPLICIT OtherRevocationInfoFormat }

      OtherRevocationInfoFormat ::= SEQUENCE {
        otherRevInfoFormat OBJECT IDENTIFIER,
        otherRevInfo ANY DEFINED BY otherRevInfoFormat }

10.2.2.  CertificateChoices

   The CertificateChoices type gives either a PKCS #6 extended
   certificate [PKCS#6], an X.509 certificate, a version 1 X.509
   attribute certificate (ACv1) [X.509-97], a version 2 X.509 attribute
   certificate (ACv2) [X.509-00], or any other certificate format.  The
   PKCS #6 extended certificate is obsolete.  The PKCS #6 certificate is
   included for backward compatibility, and PKCS #6 certificates SHOULD
   NOT be used.  The ACv1 is also obsolete.  ACv1 is included for
   backward compatibility, and ACv1 SHOULD NOT be used.  The Internet
   profile of X.509 certificates is specified in the "Internet X.509
   Public Key Infrastructure: Certificate and CRL Profile" [PROFILE].
   The Internet profile of ACv2 is specified in the "An Internet
   Attribute Certificate Profile for Authorization" [ACPROFILE].  The
   OtherCertificateFormat alternative is provided to support any other
   certificate format without further modifications to the CMS.

   The definition of Certificate is taken from X.509.

   The definitions of AttributeCertificate are taken from X.509-1997 and
   X.509-2000.  The definition from X.509-1997 is assigned to
   AttributeCertificateV1 (see section 12.2), and the definition from
   X.509-2000 is assigned to AttributeCertificateV2.

      CertificateChoices ::= CHOICE {
       certificate Certificate,
       extendedCertificate [0] IMPLICIT ExtendedCertificate, -- Obsolete
       v1AttrCert [1] IMPLICIT AttributeCertificateV1,       -- Obsolete
       v2AttrCert [2] IMPLICIT AttributeCertificateV2,
       other [3] IMPLICIT OtherCertificateFormat }

      OtherCertificateFormat ::= SEQUENCE {
       otherCertFormat OBJECT IDENTIFIER,
       otherCert ANY DEFINED BY otherCertFormat }

10.2.3.  CertificateSet

   The CertificateSet type provides a set of certificates.  It is
   intended that the set be sufficient to contain certification paths
   from a recognized "root" or "top-level certification authority" to
   all of the sender certificates with which the set is associated.
   However, there may be more certificates than necessary, or there MAY
   be fewer than necessary.

   The precise meaning of a "certification path" is outside the scope of
   this document.  However, [PROFILE] provides a definition for X.509
   certificates.  Some applications may impose upper limits on the
   length of a certification path; others may enforce certain
   relationships between the subjects and issuers of certificates within
   a certification path.

      CertificateSet ::= SET OF CertificateChoices

10.2.4.  IssuerAndSerialNumber

   The IssuerAndSerialNumber type identifies a certificate, and thereby
   an entity and a public key, by the distinguished name of the
   certificate issuer and an issuer-specific certificate serial number.

   The definition of Name is taken from X.501 [X.501-88], and the
   definition of CertificateSerialNumber is taken from X.509 [X.509-97].

      IssuerAndSerialNumber ::= SEQUENCE {
        issuer Name,
        serialNumber CertificateSerialNumber }

      CertificateSerialNumber ::= INTEGER

10.2.5.  CMSVersion

   The CMSVersion type gives a syntax version number, for compatibility
   with future revisions of this specification.

      CMSVersion ::= INTEGER
                     { v0(0), v1(1), v2(2), v3(3), v4(4), v5(5) }

10.2.6.  UserKeyingMaterial

   The UserKeyingMaterial type gives a syntax for user keying material
   (UKM).  Some key agreement algorithms require UKMs to ensure that a
   different key is generated each time the same two parties generate a
   pairwise key.  The sender provides a UKM for use with a specific key
   agreement algorithm.

      UserKeyingMaterial ::= OCTET STRING

10.2.7.  OtherKeyAttribute

   The OtherKeyAttribute type gives a syntax for the inclusion of other
   key attributes that permit the recipient to select the key used by
   the sender.  The attribute object identifier must be registered along
   with the syntax of the attribute itself.  Use of this structure
   should be avoided since it might impede interoperability.

      OtherKeyAttribute ::= SEQUENCE {
        keyAttrId OBJECT IDENTIFIER,
        keyAttr ANY DEFINED BY keyAttrId OPTIONAL }

11.  Useful Attributes

   This section defines attributes that may be used with signed-data,
   enveloped-data, encrypted-data, or authenticated-data.  The syntax of
   Attribute is compatible with X.501 [X.501-88] and RFC 3280 [PROFILE].
   Some of the attributes defined in this section were originally
   defined in PKCS #9 [PKCS#9]; others were originally defined in a
   previous version of this specification [CMS1].  The attributes are
   not listed in any particular order.

   Additional attributes are defined in many places, notably the S/MIME
   Version 3 Message Specification [MSG] and the Enhanced Security
   Services for S/MIME [ESS], which also include recommendations on the
   placement of these attributes.

11.1.  Content Type

   The content-type attribute type specifies the content type of the
   ContentInfo within signed-data or authenticated-data.  The content-
   type attribute type MUST be present whenever signed attributes are
   present in signed-data or authenticated attributes present in
   authenticated-data.  The content-type attribute value MUST match the
   encapContentInfo eContentType value in the signed-data or
   authenticated-data.

   The content-type attribute MUST be a signed attribute or an
   authenticated attribute; it MUST NOT be an unsigned attribute,
   unauthenticated attribute, or unprotected attribute.

   The following object identifier identifies the content-type
   attribute:

      id-contentType OBJECT IDENTIFIER ::= { iso(1) member-body(2)
          us(840) rsadsi(113549) pkcs(1) pkcs9(9) 3 }

   Content-type attribute values have ASN.1 type ContentType:

      ContentType ::= OBJECT IDENTIFIER

   Even though the syntax is defined as a SET OF AttributeValue, a
   content-type attribute MUST have a single attribute value; zero or
   multiple instances of AttributeValue are not permitted.

   The SignedAttributes and AuthAttributes syntaxes are each defined as
   a SET OF Attributes.  The SignedAttributes in a signerInfo MUST NOT
   include multiple instances of the content-type attribute.  Similarly,
   the AuthAttributes in an AuthenticatedData MUST NOT include multiple
   instances of the content-type attribute.

11.2.  Message Digest

   The message-digest attribute type specifies the message digest of the
   encapContentInfo eContent OCTET STRING being signed in signed-data
   (see section 5.4) or authenticated in authenticated-data (see section
   9.2).  For signed-data, the message digest is computed using the
   signer's message digest algorithm.  For authenticated-data, the
   message digest is computed using the originator's message digest
   algorithm.

   Within signed-data, the message-digest signed attribute type MUST be
   present when there are any signed attributes present.  Within
   authenticated-data, the message-digest authenticated attribute type
   MUST be present when there are any authenticated attributes present.

   The message-digest attribute MUST be a signed attribute or an
   authenticated attribute; it MUST NOT be an unsigned attribute,
   unauthenticated attribute, or unprotected attribute.

   The following object identifier identifies the message-digest
   attribute:

      id-messageDigest OBJECT IDENTIFIER ::= { iso(1) member-body(2)
          us(840) rsadsi(113549) pkcs(1) pkcs9(9) 4 }

   Message-digest attribute values have ASN.1 type MessageDigest:

      MessageDigest ::= OCTET STRING

   A message-digest attribute MUST have a single attribute value, even
   though the syntax is defined as a SET OF AttributeValue.  There MUST
   NOT be zero or multiple instances of AttributeValue present.

   The SignedAttributes syntax and AuthAttributes syntax are each
   defined as a SET OF Attributes.  The SignedAttributes in a signerInfo
   MUST include only one instance of the message-digest attribute.
   Similarly, the AuthAttributes in an AuthenticatedData MUST include
   only one instance of the message-digest attribute.

11.3.  Signing Time

   The signing-time attribute type specifies the time at which the
   signer (purportedly) performed the signing process.  The signing-time
   attribute type is intended for use in signed-data.

   The signing-time attribute MUST be a signed attribute or an
   authenticated attribute; it MUST NOT be an unsigned attribute,
   unauthenticated attribute, or unprotected attribute.

   The following object identifier identifies the signing-time
   attribute:

      id-signingTime OBJECT IDENTIFIER ::= { iso(1) member-body(2)
          us(840) rsadsi(113549) pkcs(1) pkcs9(9) 5 }

   Signing-time attribute values have ASN.1 type SigningTime:

      SigningTime ::= Time

      Time ::= CHOICE {
        utcTime UTCTime,
        generalizedTime GeneralizedTime }

   Note: The definition of Time matches the one specified in the 1997
   version of X.509 [X.509-97].

   Dates between 1 January 1950 and 31 December 2049 (inclusive) MUST be
   encoded as UTCTime.  Any dates with year values before 1950 or after
   2049 MUST be encoded as GeneralizedTime.

   UTCTime values MUST be expressed in Coordinated Universal Time
   (formerly known as Greenwich Mean Time (GMT) and Zulu clock time) and
   MUST include seconds (i.e., times are YYMMDDHHMMSSZ), even where the
   number of seconds is zero.  Midnight MUST be represented as
   "YYMMDD000000Z".  Century information is implicit, and the century
   MUST be determined as follows:

      Where YY is greater than or equal to 50, the year MUST be
      interpreted as 19YY; and

      Where YY is less than 50, the year MUST be interpreted as 20YY.

   GeneralizedTime values MUST be expressed in Coordinated Universal
   Time and MUST include seconds (i.e., times are YYYYMMDDHHMMSSZ), even
   where the number of seconds is zero.  GeneralizedTime values MUST NOT
   include fractional seconds.

   A signing-time attribute MUST have a single attribute value, even
   though the syntax is defined as a SET OF AttributeValue.  There MUST
   NOT be zero or multiple instances of AttributeValue present.

   The SignedAttributes syntax and the AuthAttributes syntax are each
   defined as a SET OF Attributes.  The SignedAttributes in a signerInfo
   MUST NOT include multiple instances of the signing-time attribute.
   Similarly, the AuthAttributes in an AuthenticatedData MUST NOT
   include multiple instances of the signing-time attribute.

   No requirement is imposed concerning the correctness of the signing
   time, and acceptance of a purported signing time is a matter of a
   recipient's discretion.  It is expected, however, that some signers,
   such as time-stamp servers, will be trusted implicitly.

11.4.  Countersignature

   The countersignature attribute type specifies one or more signatures
   on the contents octets of the signature OCTET STRING in a SignerInfo
   value of the signed-data.  That is, the message digest is computed
   over the octets comprising the value of the OCTET STRING, neither the
   tag nor length octets are included.  Thus, the countersignature
   attribute type countersigns (signs in serial) another signature.

   The countersignature attribute MUST be an unsigned attribute; it MUST
   NOT be a signed attribute, an authenticated attribute, an
   unauthenticated attribute, or an unprotected attribute.

   The following object identifier identifies the countersignature
   attribute:

      id-countersignature OBJECT IDENTIFIER ::= { iso(1) member-body(2)
          us(840) rsadsi(113549) pkcs(1) pkcs9(9) 6 }

   Countersignature attribute values have ASN.1 type Countersignature:

      Countersignature ::= SignerInfo

   Countersignature values have the same meaning as SignerInfo values
   for ordinary signatures, except that:

      1. The signedAttributes field MUST NOT contain a content-type
         attribute; there is no content type for countersignatures.

      2. The signedAttributes field MUST contain a message-digest
         attribute if it contains any other attributes.

      3. The input to the message-digesting process is the contents
         octets of the DER encoding of the signatureValue field of the
         SignerInfo value with which the attribute is associated.

   A countersignature attribute can have multiple attribute values.  The
   syntax is defined as a SET OF AttributeValue, and there MUST be one
   or more instances of AttributeValue present.

   The UnsignedAttributes syntax is defined as a SET OF Attributes.  The
   UnsignedAttributes in a signerInfo may include multiple instances of
   the countersignature attribute.

   A countersignature, since it has type SignerInfo, can itself contain
   a countersignature attribute.  Thus, it is possible to construct an
   arbitrarily long series of countersignatures.

12.  ASN.1 Modules

   Section 12.1 contains the ASN.1 module for the CMS, and section 12.2
   contains the ASN.1 module for the Version 1 Attribute Certificate.

12.1.  CMS ASN.1 Module

   CryptographicMessageSyntax2004
     { iso(1) member-body(2) us(840) rsadsi(113549)
       pkcs(1) pkcs-9(9) smime(16) modules(0) cms-2004(24) }

   DEFINITIONS IMPLICIT TAGS ::=
   BEGIN

   -- EXPORTS All
   -- The types and values defined in this module are exported for use
   -- in the other ASN.1 modules.  Other applications may use them for
   -- their own purposes.

   IMPORTS

     -- Imports from RFC 3280 [PROFILE], Appendix A.1
           AlgorithmIdentifier, Certificate, CertificateList,
           CertificateSerialNumber, Name
              FROM PKIX1Explicit88
                   { iso(1) identified-organization(3) dod(6)
                     internet(1) security(5) mechanisms(5) pkix(7)
                     mod(0) pkix1-explicit(18) }

     -- Imports from RFC 3281 [ACPROFILE], Appendix B
           AttributeCertificate
              FROM PKIXAttributeCertificate
                   { iso(1) identified-organization(3) dod(6)
                     internet(1) security(5) mechanisms(5) pkix(7)
                     mod(0) attribute-cert(12) }

     -- Imports from Appendix B of this document
           AttributeCertificateV1
              FROM AttributeCertificateVersion1
                   { iso(1) member-body(2) us(840) rsadsi(113549)
                     pkcs(1) pkcs-9(9) smime(16) modules(0)
                     v1AttrCert(15) } ;

   -- Cryptographic Message Syntax

   ContentInfo ::= SEQUENCE {
     contentType ContentType,
     content [0] EXPLICIT ANY DEFINED BY contentType }

   ContentType ::= OBJECT IDENTIFIER

   SignedData ::= SEQUENCE {
     version CMSVersion,
     digestAlgorithms DigestAlgorithmIdentifiers,
     encapContentInfo EncapsulatedContentInfo,
     certificates [0] IMPLICIT CertificateSet OPTIONAL,
     crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,
     signerInfos SignerInfos }

   DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier

   SignerInfos ::= SET OF SignerInfo

   EncapsulatedContentInfo ::= SEQUENCE {
     eContentType ContentType,
     eContent [0] EXPLICIT OCTET STRING OPTIONAL }

   SignerInfo ::= SEQUENCE {
     version CMSVersion,
     sid SignerIdentifier,
     digestAlgorithm DigestAlgorithmIdentifier,
     signedAttrs [0] IMPLICIT SignedAttributes OPTIONAL,
     signatureAlgorithm SignatureAlgorithmIdentifier,
     signature SignatureValue,
     unsignedAttrs [1] IMPLICIT UnsignedAttributes OPTIONAL }

   SignerIdentifier ::= CHOICE {
     issuerAndSerialNumber IssuerAndSerialNumber,
     subjectKeyIdentifier [0] SubjectKeyIdentifier }

   SignedAttributes ::= SET SIZE (1..MAX) OF Attribute

   UnsignedAttributes ::= SET SIZE (1..MAX) OF Attribute

   Attribute ::= SEQUENCE {
     attrType OBJECT IDENTIFIER,
     attrValues SET OF AttributeValue }

   AttributeValue ::= ANY

   SignatureValue ::= OCTET STRING

   EnvelopedData ::= SEQUENCE {
     version CMSVersion,
     originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
     recipientInfos RecipientInfos,
     encryptedContentInfo EncryptedContentInfo,
     unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }

   OriginatorInfo ::= SEQUENCE {
     certs [0] IMPLICIT CertificateSet OPTIONAL,
     crls [1] IMPLICIT RevocationInfoChoices OPTIONAL }

   RecipientInfos ::= SET SIZE (1..MAX) OF RecipientInfo

   EncryptedContentInfo ::= SEQUENCE {
     contentType ContentType,
     contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
     encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL }

   EncryptedContent ::= OCTET STRING

   UnprotectedAttributes ::= SET SIZE (1..MAX) OF Attribute

   RecipientInfo ::= CHOICE {
     ktri KeyTransRecipientInfo,
     kari [1] KeyAgreeRecipientInfo,
     kekri [2] KEKRecipientInfo,
     pwri [3] PasswordRecipientInfo,
     ori [4] OtherRecipientInfo }

   EncryptedKey ::= OCTET STRING

   KeyTransRecipientInfo ::= SEQUENCE {
     version CMSVersion,  -- always set to 0 or 2
     rid RecipientIdentifier,
     keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
     encryptedKey EncryptedKey }

   RecipientIdentifier ::= CHOICE {
     issuerAndSerialNumber IssuerAndSerialNumber,
     subjectKeyIdentifier [0] SubjectKeyIdentifier }

   KeyAgreeRecipientInfo ::= SEQUENCE {
     version CMSVersion,  -- always set to 3
     originator [0] EXPLICIT OriginatorIdentifierOrKey,
     ukm [1] EXPLICIT UserKeyingMaterial OPTIONAL,
     keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
     recipientEncryptedKeys RecipientEncryptedKeys }

   OriginatorIdentifierOrKey ::= CHOICE {
     issuerAndSerialNumber IssuerAndSerialNumber,
     subjectKeyIdentifier [0] SubjectKeyIdentifier,
     originatorKey [1] OriginatorPublicKey }

   OriginatorPublicKey ::= SEQUENCE {
     algorithm AlgorithmIdentifier,
     publicKey BIT STRING }

   RecipientEncryptedKeys ::= SEQUENCE OF RecipientEncryptedKey

   RecipientEncryptedKey ::= SEQUENCE {
     rid KeyAgreeRecipientIdentifier,
     encryptedKey EncryptedKey }

   KeyAgreeRecipientIdentifier ::= CHOICE {
     issuerAndSerialNumber IssuerAndSerialNumber,
     rKeyId [0] IMPLICIT RecipientKeyIdentifier }

   RecipientKeyIdentifier ::= SEQUENCE {
     subjectKeyIdentifier SubjectKeyIdentifier,
     date GeneralizedTime OPTIONAL,
     other OtherKeyAttribute OPTIONAL }

   SubjectKeyIdentifier ::= OCTET STRING

   KEKRecipientInfo ::= SEQUENCE {
     version CMSVersion,  -- always set to 4
     kekid KEKIdentifier,
     keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
     encryptedKey EncryptedKey }

   KEKIdentifier ::= SEQUENCE {
     keyIdentifier OCTET STRING,
     date GeneralizedTime OPTIONAL,
     other OtherKeyAttribute OPTIONAL }

   PasswordRecipientInfo ::= SEQUENCE {
     version CMSVersion,   -- always set to 0
     keyDerivationAlgorithm [0] KeyDerivationAlgorithmIdentifier
                                OPTIONAL,
     keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
     encryptedKey EncryptedKey }

   OtherRecipientInfo ::= SEQUENCE {
     oriType OBJECT IDENTIFIER,
     oriValue ANY DEFINED BY oriType }

   DigestedData ::= SEQUENCE {
     version CMSVersion,
     digestAlgorithm DigestAlgorithmIdentifier,
     encapContentInfo EncapsulatedContentInfo,
     digest Digest }

   Digest ::= OCTET STRING

   EncryptedData ::= SEQUENCE {
     version CMSVersion,
     encryptedContentInfo EncryptedContentInfo,
     unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }

   AuthenticatedData ::= SEQUENCE {
     version CMSVersion,
     originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
     recipientInfos RecipientInfos,
     macAlgorithm MessageAuthenticationCodeAlgorithm,
     digestAlgorithm [1] DigestAlgorithmIdentifier OPTIONAL,
     encapContentInfo EncapsulatedContentInfo,
     authAttrs [2] IMPLICIT AuthAttributes OPTIONAL,
     mac MessageAuthenticationCode,
     unauthAttrs [3] IMPLICIT UnauthAttributes OPTIONAL }

   AuthAttributes ::= SET SIZE (1..MAX) OF Attribute

   UnauthAttributes ::= SET SIZE (1..MAX) OF Attribute

   MessageAuthenticationCode ::= OCTET STRING

   DigestAlgorithmIdentifier ::= AlgorithmIdentifier

   SignatureAlgorithmIdentifier ::= AlgorithmIdentifier

   KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier

   ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier

   MessageAuthenticationCodeAlgorithm ::= AlgorithmIdentifier

   KeyDerivationAlgorithmIdentifier ::= AlgorithmIdentifier

   RevocationInfoChoices ::= SET OF RevocationInfoChoice

   RevocationInfoChoice ::= CHOICE {
     crl CertificateList,
     other [1] IMPLICIT OtherRevocationInfoFormat }

   OtherRevocationInfoFormat ::= SEQUENCE {
     otherRevInfoFormat OBJECT IDENTIFIER,
     otherRevInfo ANY DEFINED BY otherRevInfoFormat }

   CertificateChoices ::= CHOICE {
     certificate Certificate,
     extendedCertificate [0] IMPLICIT ExtendedCertificate,  -- Obsolete
     v1AttrCert [1] IMPLICIT AttributeCertificateV1,        -- Obsolete
     v2AttrCert [2] IMPLICIT AttributeCertificateV2,
     other [3] IMPLICIT OtherCertificateFormat }

   AttributeCertificateV2 ::= AttributeCertificate

   OtherCertificateFormat ::= SEQUENCE {
     otherCertFormat OBJECT IDENTIFIER,
     otherCert ANY DEFINED BY otherCertFormat }

   CertificateSet ::= SET OF CertificateChoices

   IssuerAndSerialNumber ::= SEQUENCE {
     issuer Name,
     serialNumber CertificateSerialNumber }

   CMSVersion ::= INTEGER  { v0(0), v1(1), v2(2), v3(3), v4(4), v5(5) }

   UserKeyingMaterial ::= OCTET STRING

   OtherKeyAttribute ::= SEQUENCE {
     keyAttrId OBJECT IDENTIFIER,
     keyAttr ANY DEFINED BY keyAttrId OPTIONAL }

   -- Content Type Object Identifiers

   id-ct-contentInfo OBJECT IDENTIFIER ::= { iso(1) member-body(2)
       us(840) rsadsi(113549) pkcs(1) pkcs9(9) smime(16) ct(1) 6 }

   id-data OBJECT IDENTIFIER ::= { iso(1) member-body(2)
       us(840) rsadsi(113549) pkcs(1) pkcs7(7) 1 }

   id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
       us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }

   id-envelopedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
       us(840) rsadsi(113549) pkcs(1) pkcs7(7) 3 }

   id-digestedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
       us(840) rsadsi(113549) pkcs(1) pkcs7(7) 5 }

   id-encryptedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
       us(840) rsadsi(113549) pkcs(1) pkcs7(7) 6 }

   id-ct-authData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
       us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1) 2 }

   -- The CMS Attributes

   MessageDigest ::= OCTET STRING

   SigningTime  ::= Time

   Time ::= CHOICE {
     utcTime UTCTime,
     generalTime GeneralizedTime }

   Countersignature ::= SignerInfo

   -- Attribute Object Identifiers

   id-contentType OBJECT IDENTIFIER ::= { iso(1) member-body(2)
       us(840) rsadsi(113549) pkcs(1) pkcs9(9) 3 }

   id-messageDigest OBJECT IDENTIFIER ::= { iso(1) member-body(2)
       us(840) rsadsi(113549) pkcs(1) pkcs9(9) 4 }

   id-signingTime OBJECT IDENTIFIER ::= { iso(1) member-body(2)
       us(840) rsadsi(113549) pkcs(1) pkcs9(9) 5 }

   id-countersignature OBJECT IDENTIFIER ::= { iso(1) member-body(2)
       us(840) rsadsi(113549) pkcs(1) pkcs9(9) 6 }

   -- Obsolete Extended Certificate syntax from PKCS#6

   ExtendedCertificateOrCertificate ::= CHOICE {
     certificate Certificate,
     extendedCertificate [0] IMPLICIT ExtendedCertificate }

   ExtendedCertificate ::= SEQUENCE {
     extendedCertificateInfo ExtendedCertificateInfo,
     signatureAlgorithm SignatureAlgorithmIdentifier,
     signature Signature }

   ExtendedCertificateInfo ::= SEQUENCE {
     version CMSVersion,
     certificate Certificate,
     attributes UnauthAttributes }

   Signature ::= BIT STRING

   END -- of CryptographicMessageSyntax2004

12.2.  Version 1 Attribute Certificate ASN.1 Module

   AttributeCertificateVersion1
       { iso(1) member-body(2) us(840) rsadsi(113549)
         pkcs(1) pkcs-9(9) smime(16) modules(0) v1AttrCert(15) }

   DEFINITIONS EXPLICIT TAGS ::=
   BEGIN

   -- EXPORTS All

   IMPORTS

     -- Imports from RFC 3280 [PROFILE], Appendix A.1
           AlgorithmIdentifier, Attribute, CertificateSerialNumber,
           Extensions, UniqueIdentifier
              FROM PKIX1Explicit88
                   { iso(1) identified-organization(3) dod(6)
                     internet(1) security(5) mechanisms(5) pkix(7)
                     mod(0) pkix1-explicit(18) }

     -- Imports from RFC 3280 [PROFILE], Appendix A.2
           GeneralNames
              FROM PKIX1Implicit88
                   { iso(1) identified-organization(3) dod(6)
                     internet(1) security(5) mechanisms(5) pkix(7)
                     mod(0) pkix1-implicit(19) }

     -- Imports from RFC 3281 [ACPROFILE], Appendix B
           AttCertValidityPeriod, IssuerSerial
              FROM PKIXAttributeCertificate
                   { iso(1) identified-organization(3) dod(6)
                     internet(1) security(5) mechanisms(5) pkix(7)
                     mod(0) attribute-cert(12) } ;

   -- Definition extracted from X.509-1997 [X.509-97], but
   -- different type names are used to avoid collisions.

   AttributeCertificateV1 ::= SEQUENCE {
     acInfo AttributeCertificateInfoV1,
     signatureAlgorithm AlgorithmIdentifier,
     signature BIT STRING }

   AttributeCertificateInfoV1 ::= SEQUENCE {
     version AttCertVersionV1 DEFAULT v1,
     subject CHOICE {
       baseCertificateID [0] IssuerSerial,
         -- associated with a Public Key Certificate
       subjectName [1] GeneralNames },
         -- associated with a name
     issuer GeneralNames,
     signature AlgorithmIdentifier,
     serialNumber CertificateSerialNumber,
     attCertValidityPeriod AttCertValidityPeriod,
     attributes SEQUENCE OF Attribute,
     issuerUniqueID UniqueIdentifier OPTIONAL,
     extensions Extensions OPTIONAL }

   AttCertVersionV1 ::= INTEGER { v1(0) }

   END -- of AttributeCertificateVersion1

13.  References

13.1.  Normative References

   [ACPROFILE]  Farrell, S. and R. Housley, "An Internet Attribute
                Certificate Profile for Authorization", RFC 3281, April
                2002.

   [PROFILE]    Housley, R., Polk, W., Ford, W., and D. Solo, "Internet
                X.509 Public Key Infrastructure Certificate and
                Certificate Revocation List (CRL) Profile", RFC 3280,
                April 2002.

   [STDWORDS]   Bradner, S., "Key words for use in RFCs to Indicate
                Requirement Levels", BCP 14, RFC 2119, March 1997.

   [X.208-88]   CCITT.  Recommendation X.208: Specification of Abstract
                Syntax Notation One (ASN.1).  1988.

   [X.209-88]   CCITT.  Recommendation X.209: Specification of Basic
                Encoding Rules for Abstract Syntax Notation One (ASN.1).
                1988.

   [X.501-88]   CCITT.  Recommendation X.501: The Directory - Models.
                1988.

   [X.509-88]   CCITT.  Recommendation X.509: The Directory -
                Authentication Framework.  1988.

   [X.509-97]   ITU-T.  Recommendation X.509: The Directory -
                Authentication Framework.  1997.

   [X.509-00]   ITU-T.  Recommendation X.509: The Directory -
                Authentication Framework.  2000.

13.2.  Informative References

   [CMS1]       Housley, R., "Cryptographic Message Syntax", RFC 2630,
                June 1999.

   [CMS2]       Housley, R., "Cryptographic Message Syntax (CMS)", RFC
                3369, August 2002.

   [CMSALG]     Housley, R., "Cryptographic Message Syntax (CMS)
                Algorithms", RFC 3370, August 2002.

   [ESS]        Hoffman, P., "Enhanced Security Services for S/MIME",
                RFC 2634, June 1999.

   [MSAC]       Microsoft Development Network (MSDN) Library,
                "Authenticode", April 2004 Release.

   [MSG]        Ramsdell, B., "S/MIME Version 3.1 Message
                Specification", RFC 3851, July 2004.

   [OCSP]       Myers, M., Ankney, R., Malpani, A., Galperin, S. and C.
                Adams, "X.509 Internet Public Key Infrastructure Online
                Certificate Status Protocol - OCSP", RFC 2560, June
                1999.

   [OLDMSG]     Dusse, S., Hoffman, P., Ramsdell, B., Lundblade, L., and
                L. Repka, "S/MIME Version 2 Message Specification", RFC
                2311, March 1998.

   [PKCS#6]     RSA Laboratories.  PKCS #6: Extended-Certificate Syntax
                Standard, Version 1.5.  November 1993.

   [PKCS#7]     Kaliski, B., "PKCS #7: Cryptographic Message Syntax
                Version 1.5", RFC 2315, March 1998.

   [PKCS#9]     RSA Laboratories.  PKCS #9: Selected Attribute Types,
                Version 1.1.  November 1993.

   [PWRI]       Gutmann, P., "Password-based Encryption for CMS", RFC
                3211, December 2001.

   [RANDOM]     Eastlake 3rd, D., Crocker, S., and J. Schiller,
                "Randomness Recommendations for Security", RFC 1750,
                December 1994.

14.  Security Considerations

   The Cryptographic Message Syntax provides a method for digitally
   signing data, digesting data, encrypting data, and authenticating
   data.

   Implementations must protect the signer's private key.  Compromise of
   the signer's private key permits masquerade.

   Implementations must protect the key management private key, the
   key-encryption key, and the content-encryption key.  Compromise of
   the key management private key or the key-encryption key may result
   in the disclosure of all contents protected with that key.
   Similarly, compromise of the content-encryption key may result in
   disclosure of the associated encrypted content.

   Implementations must protect the key management private key and the
   message-authentication key.  Compromise of the key management private
   key permits masquerade of authenticated data.  Similarly, compromise
   of the message-authentication key may result in undetectable
   modification of the authenticated content.

   The key management technique employed to distribute message-
   authentication keys must itself provide data origin authentication,
   otherwise the contents are delivered with integrity from an unknown
   source.  Neither RSA [PKCS#1, NEWPKCS#1] nor Ephemeral-Static
   Diffie-Hellman [DH-X9.42] provide the necessary data origin
   authentication.  Static-Static Diffie-Hellman [DH-X9.42] does provide
   the necessary data origin authentication when both the originator and
   recipient public keys are bound to appropriate identities in X.509
   certificates.

   When more than two parties share the same message-authentication key,
   data origin authentication is not provided.  Any party that knows the
   message-authentication key can compute a valid MAC, therefore the
   contents could originate from any one of the parties.

   Implementations must randomly generate content-encryption keys,
   message-authentication keys, initialization vectors (IVs), and
   padding.  Also, the generation of public/private key pairs relies on
   a random numbers.  The use of inadequate pseudo-random number
   generators (PRNGs) to generate cryptographic keys can result in
   little or no security.  An attacker may find it much easier to
   reproduce the PRNG environment that produced the keys, searching the
   resulting small set of possibilities, rather than brute force
   searching the whole key space.  The generation of quality random
   numbers is difficult.  RFC 1750 [RANDOM] offers important guidance in
   this area.

   When using key agreement algorithms or previously distributed
   symmetric key-encryption keys, a key-encryption key is used to
   encrypt the content-encryption key.  If the key-encryption and
   content-encryption algorithms are different, the effective security
   is determined by the weaker of the two algorithms.  If, for example,
   content is encrypted with Triple-DES using a 168-bit Triple-DES
   content-encryption key, and the content-encryption key is wrapped
   with RC2 using a 40-bit RC2 key-encryption key, then at most 40 bits
   of protection is provided.  A trivial search to determine the value
   of the 40-bit RC2 key can recover the Triple-DES key, and then the
   Triple-DES key can be used to decrypt the content.  Therefore,
   implementers must ensure that key-encryption algorithms are as strong
   or stronger than content-encryption algorithms.

   Implementers should be aware that cryptographic algorithms become
   weaker with time.  As new cryptoanalysis techniques are developed and
   computing performance improves, the work factor to break a particular
   cryptographic algorithm will be reduced.  Therefore, cryptographic
   algorithm implementations should be modular, allowing new algorithms
   to be readily inserted.  That is, implementors should be prepared for
   the set of algorithms that must be supported to change over time.

   The countersignature unsigned attribute includes a digital signature
   that is computed on the content signature value, thus the
   countersigning process need not know the original signed content.
   This structure permits implementation efficiency advantages; however,
   this structure may also permit the countersigning of an inappropriate
   signature value.  Therefore, implementations that perform
   countersignatures should either verify the original signature value
   prior to countersigning it (this verification requires processing of
   the original content), or implementations should perform
   countersigning in a context that ensures that only appropriate
   signature values are countersigned.

15.  Acknowledgments

   This document is the result of contributions from many professionals.
   I appreciate the hard work of all members of the IETF S/MIME Working
   Group.  I extend a special thanks to Rich Ankney, Simon Blake-Wilson,
   Tim Dean, Steve Dusse, Carl Ellison, Peter Gutmann, Bob Jueneman,
   Stephen Henson, Paul Hoffman, Scott Hollenbeck, Don Johnson, Burt
   Kaliski, John Linn, John Pawling, Blake Ramsdell, Francois Rousseau,
   Jim Schaad, Dave Solo, Paul Timmel, and Sean Turner for their efforts
   and support.

16.  Author's Address

   Russell Housley
   Vigil Security, LLC
   918 Spring Knoll Drive
   Herndon, VA 20170
   USA

   EMail: housley@vigilsec.com

17.  Full Copyright Statement

   Copyright (C) The Internet Society (2004).  This document is subject
   to the rights, licenses and restrictions contained in BCP 78, and
   except as set forth therein, the authors retain all their rights.

   This document and the information contained herein are provided on an
   "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS
   OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET
   ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED,
   INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE
   INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED
   WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.

Intellectual Property

   The IETF takes no position regarding the validity or scope of any
   Intellectual Property Rights or other rights that might be claimed to
   pertain to the implementation or use of the technology described in
   this document or the extent to which any license under such rights
   might or might not be available; nor does it represent that it has
   made any independent effort to identify any such rights.  Information
   on the procedures with respect to rights in RFC documents can be
   found in BCP 78 and BCP 79.

   Copies of IPR disclosures made to the IETF Secretariat and any
   assurances of licenses to be made available, or the result of an
   attempt made to obtain a general license or permission for the use of
   such proprietary rights by implementers or users of this
   specification can be obtained from the IETF on-line IPR repository at
   http://www.ietf.org/ipr.

   The IETF invites any interested party to bring to its attention any
   copyrights, patents or patent applications, or other proprietary
   rights that may cover technology that may be required to implement
   this standard.  Please address the information to the IETF at ietf-
   ipr@ietf.org.

Acknowledgement

   Funding for the RFC Editor function is currently provided by the
   Internet Society.


'프로그래밍' 카테고리의 다른 글

개발자의 심리학  (2) 2009.10.01
RFC3852 - Cryptographic Message Syntax(CMS)  (0) 2009.07.30
공인인증서로 전자서명하기  (0) 2009.07.27
ASN.1  (1) 2009.07.27

태그

댓글 0

공인인증서로 전자서명하기

2009. 7. 27.

인터넷 뱅킹을 하시는 분이라면 대부분 공인인증서를 가지고 있다. 이 공인인증서를 가지고 전자서명을 해보도록하자(전혀 쓸데없는 일이긴 하다 ^^;)
필자의 경우 yessign에서 발급한 은행용 공인인증서를 가지고 있는데 그 경로는 C:\NPKI\yessign\USER\아래폴더... 에 위치해 있다.
그 디렉토리에 보면 CaPubs, signCert.der, signPri.key 세 파일이 존재한다.
CaPubs은 무슨 파일인지 잘 모르겠다. signCert.der는 공인 인증서 파일이고, signPri.key는 개인키 파일이다.
(der은 인증서 저장시 바이너르 형태로 저장하기 위한 포맷이고, pem은 문자열로 표현가능한 데이터로 인코딩(BASE64같은..)한 포맷이다.)
한국정보보호진흥원(http://www.rootca.or.kr/kcac.html)의 기술규격을 참조해보면, 현재 사용하는 공인인증서는 RFC3280을 준수하여, 전자서명인증체계에서 사용하는 정수2를 갖는 X.509 v3을 사용하고 있다고 한다.

1. 공개키 가져오기.
 - 자바에서 X.590를 지원해주니 간단히 사용해보자.
package test.security;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
 
public class CertificateTest1 {
 
	public static void main(String[] args) throws Exception {
		X509Certificate cert = null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(new File("C:/signCert.der"));
			CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
			cert = (X509Certificate) certificateFactory.generateCertificate(fis);
		} finally {
			if (fis != null) try {fis.close();} catch(IOException ie) {}
		}
		System.out.println(cert);
		System.out.println("-----------------");
		System.out.println(cert.getPublicKey());
	}
}

실행해보면 아래처럼 인증서에 대한 정보를 볼 수 있을것이다.(보안 관계상 많은 부분을 생략하겠다.)

[
[
  Version: V3
  Subject: CN=누굴까(RangWoo)0000000000000000, OU=XXX, OU=personalXXX, O=yessign, C=kr
  Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5

  Key:  Sun RSA public key, 1024 bits
... 생략 ...
[7]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
  [accessMethod: 1.3.6.1.5.5.7.48.1
   accessLocation: URIName: http://ocsp.yessign.org:4612]
]
... 생략 ...
Sun RSA public key, 1024 bits
  modulus: 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
  public exponent: 00000

당연히, V3 버젼을 사용하고 서명 알고리즘은 SHA1withRSA을 사용한다. SHA1withRSA 옆에 보면 OID란 놈이 있다.
OID란 Object IDentifier의 약어로서 객체식별체계정도로 이해하면 되겠다. 즉, OID의 값이 1.2.840.113549.1.1.5이면 SHA1withRSA란 의미이다.
http://www.oid-info.com/ 사이트에 가서 1.2.840.113549.1.1.5 값을 입력하면 아래와 같은 값을 얻을 수 있다.

그리고 중간쯤에 ocsp(Online Certificate Status Protocol)라고 실시간으로 인증서 유효성 검증을 할수 있는 정보도 나온다.
좀더 내려가보면 공개키부분이 나오는데, 이놈이 우리가 사용할 부분이다. cert.getPublicKey() 메소드를 이용하면 직접 공개키를 가져올 수 있다.

2. 개인키 가져오기
 - 공개키는 거의 날로 먹었는데, 개인키란 놈은 만만하지가 않다.
 - 기본적으로(?)는 PKCS#8를 이용해서 개인키를 저장하는데, 국내 공인인증서에 사용하는 개인키 파일는 암호화(?)해서 저장한다.
PKCS#5(Password-Based Cryptography Standard)의 PBKDF1(Password-Based Key Derivation Function), PBES1(Password-Based Encryption Scheme)를 이용한다는 것이다.
여기까지는 별 문제가 없는데, 데이터 암호화를 할때 국내에서만 사용하는 SEED란 블럭암호화 알고리즘를 사용한다는것이다.
즉, 기본적으로 제공이 안되므로 직접 구현을 해야한다.
뭔소리인지 이해가 안가면 한국정보보호진흥원(http://www.rootca.or.kr/)의 암호 알고리즘 규격(KCAC.TS.ENC)를 한번 읽어보자. (사실 읽어봐도 이해가 안가지만... ^^;)
  간단히 설명을 하자면, PBES(Password-Based Encryption Scheme) 즉 패스워드 기반의 키 암호화 기법을 사용하겠다는 것이다. 암호화 할때 필요한게 비밀키이다. 이 키는 해당 알고리즘에 맞는 바이트 배열로 보통 사용을 하는데, 이것을 사람이 쉽게 인식할 수 있는 패스워드로 사용하겠다는것이다.
 뭐 필자처럼 무식하게 "hello123".getBytes(); 를 사용해서 키로 사용할 수 있지만, 모양새가 안좋아보인다는것이다. 그래서 "hello123" 문자열을 가공해서 멋진(?) 키로 만들어 사용한다는 것이다.
이 가공하는 함수가 PBKDF(Password-Based Key Derivation Function)이다. 그리고 이 함수를 이용해서 비밀키를 생성해서 암호화/복화하는 하는 구조를 PBES라고 한다.
자바에서 기본적으로 "PBEWithMD5AndDES", "PBEWithSHA1AndDESede" 등의 알고리즘을 제공해준다.
Security.getProviders(); 메소드를 이용해서, Provider 정보를 출력해보면 지원하는 알고리즘을 알 수 있다.
package test.security;
 
import java.security.Provider;
import java.security.Security;
 
public class ProviderInfo {
 
	public static void main(String[] args) {
		Provider[] providers = Security.getProviders();
		for (int i = 0; i < providers.length; i++) {
			String name = providers[i].getName();
			String info = providers[i].getInfo();
			double version = providers[i].getVersion();
			System.out.println("--------------------------------------------------");
			System.out.println("name: " + name);
			System.out.println("info: " + info);
			System.out.println("version: " + version);
 
			for (Object key : providers[i].keySet()) {
				System.out.println(key + "\t"+ providers[i].getProperty((String)key));
			}
		}
	}
}

그런데 불행히도 "PBEWithSHA1AndSeed"같은 알고리즘은 없는거 같다. 어떻게 해야할까? 당연히 삽~을 들어야한다.(아~~ 또 무덤을 파는구나 ㅠㅠ)
일단 파일의 구조를 파악해서 필요한 정보를 읽어와야한다.(ASN. 1으로 인코딩되어있다.)
다행히도 PKCS#8로 정의하고 있는 구조를 읽을 수 있는 EncryptedPrivateKeyInfo 클래스가 존재해서 한결 쉽게 작업을 할 수 있다
EncryptedPrivateKeyInfo 클래스를 사용해서 정보를 읽어오자. 사용하는 알고리즘을 출력해 보자.
		// 1. 개인키 파일 읽어오기
		byte[] encodedKey = null;
		FileInputStream fis = null;
		ByteArrayOutputStream bos = null;
		try {
			fis = new FileInputStream(new File("C:/signPri.key"));
			bos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int read = -1;
			while ((read = fis.read(buffer)) != -1) {
				bos.write(buffer, 0, read);
			}
			encodedKey = bos.toByteArray();
		} finally {
			if (bos != null) try {bos.close();} catch(IOException ie) {}
			if (fis != null) try {fis.close();} catch(IOException ie) {}
		}
 
		System.out.println("EncodedKey : " + ByteUtils.toHexString(encodedKey));
		
		// 2. 개인카 파일 분석하기
		EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(encodedKey);
		System.out.println(encryptedPrivateKeyInfo);
		System.out.println(encryptedPrivateKeyInfo.getAlgName());

필자의 경우  "1.2.410.200004.1.15"란 값을 얻을 수 있었다. 나머지 파라메터 정보는 불행히도 제공을 안해줘서 직접 처리해야한다.
"1.2.410.200004.1.15" 어디서 많이 본 형식이다. 그렇다. OID이다. 사이트(http://www.oid-info.com/)가서 조회를 해보자.
"Key Generation with SHA1 and Encryption with SEED CBC mode" 란다.

한국정보보호진흥원(http://www.rootca.or.kr/)의 암호 알고리즘 규격(KCAC.TS.ENC)에서도 해당 OID에 대한 정보를 알 수 있다.

  즉, 두 번째 방법이라는 것인데, DK의 값을 이용해서 해쉬값을 만든다음 그 값을 IV(초기화 벡터)로 사용하라는 것이다.
 여기서 DK란 PBKDF를 사용해서 만든 추출키를 의미한다. 그렇다면 먼저 추출키를 만들어보자.

  위의 설명대로 해당 함수를 구현해보자.
 salt와 iteration count가 필요하다.
 salt는 공인인증서를 발급할때마다 랜덤하게 생성되는것으로, 블특정다수의 사전(Dictionary) 공격을 방지하는 역할을 한다.(21-28바이트 사이의 8바이트를 사용함)
 iteration count는 비밀키 생성을 위해 해쉬함수를 몇번 반복할 것인가를 나타낸다. (31-32바이트 사이의 2바이트를 사용함)
		byte[] salt = new byte[8];
		System.arraycopy(encodedKey, 20, salt, 0, 8);
		System.out.println("salt : " + ByteUtils.toHexString(salt));
		byte[] cBytes = new byte[4];
		System.arraycopy(encodedKey, 30, cBytes, 2, 2);
		int iterationCount = ByteUtils.toInt(cBytes);
		System.out.println("iterationCount : " + ByteUtils.toHexString(cBytes));
		System.out.println("iterationCount : " + iterationCount);

그럼 PBKDF1을 구현해보자. RFC2898(http://www.ietf.org/rfc/rfc2898.txt)을 보면 아래처럼 설명이 나와있다.
5.1 PBKDF1
 
   PBKDF1 applies a hash function, which shall be MD2 [6], MD5 [19] or
   SHA-1 [18], to derive keys. The length of the derived key is bounded
   by the length of the hash function output, which is 16 octets for MD2
   and MD5 and 20 octets for SHA-1. PBKDF1 is compatible with the key
   derivation process in PKCS #5 v1.5.
 
   PBKDF1 is recommended only for compatibility with existing
   applications since the keys it produces may not be large enough for
   some applications.
 
   PBKDF1 (P, S, c, dkLen)
 
   Options:        Hash       underlying hash function
 
   Input:          P          password, an octet string
                   S          salt, an eight-octet string
                   c          iteration count, a positive integer
                   dkLen      intended length in octets of derived key,
                              a positive integer, at most 16 for MD2 or
                              MD5 and 20 for SHA-1
 
   Output:         DK         derived key, a dkLen-octet string
 
   Steps:
 
      1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output
         "derived key too long" and stop.
 
      2. Apply the underlying hash function Hash for c iterations to the
         concatenation of the password P and the salt S, then extract
         the first dkLen octets to produce a derived key DK:
 
                   T_1 = Hash (P || S) ,
                   T_2 = Hash (T_1) ,
                   ...
                   T_c = Hash (T_{c-1}) ,
                   DK = Tc<0..dkLen-1>
 
      3. Output the derived key DK.
  설명대로 구현해주자. 피곤한 관계상 SHA1을 사용해서 20바이트의 추출키만을 반환하도록 만들었다.
	public static byte[] pbkdf1(String password, byte[] salt, int iterationCount) throws NoSuchAlgorithmException {
		byte[] dk = new byte[20];
		MessageDigest md = MessageDigest.getInstance("SHA1");
		md.update(password.getBytes());
		md.update(salt);
		dk = md.digest();
		for (int i = 1; i < iterationCount; i++) {
			dk = md.digest(dk);
		}
		return dk;
	}
}

해당 함수를 사용해서 추출키(DK) 초기화 벡터(IV)를 만들어 보자.
		String password = "password";
 
		// 추출키(DK) 생성
		byte[] dk = pbkdf1(password, salt, iterationCount);
		System.out.println("dk : " + ByteUtils.toHexString(dk));
		
		// 생성된 추출키(DK)에서 처음 16바이트를 암호화 키(K)로 정의한다.
		byte[] keyData = new byte[16];
		System.arraycopy(dk, 0, keyData, 0, 16);
		
	    // 추출키(DK)에서 암호화 키(K)를 제외한 나머지 4바이트를 SHA-1
	    // 으로 해쉬하여 20바이트의 값(DIV)을 생성하고,  그 중 처음 16바이트를 초기 
	    // 벡터(IV)로 정의한다.
		byte[] div = new byte[20];
		byte[] tmp4Bytes = new byte[4];
		System.arraycopy(dk, 16, tmp4Bytes, 0, 4);
		div = SHA1Utils.getHash(tmp4Bytes);
		System.out.println("div : " + ByteUtils.toHexString(div));
		byte[] iv = new byte[16];
		System.arraycopy(div, 0, iv, 0, 16);
		System.out.println("iv : " + ByteUtils.toHexString(iv));

당연히 password 변수에는 공인인증서 암호를 입력해야한다. 안그러면 에러가 난다.
이제 고지가 눈앞에 보인다. 남은것은 SEED를 이용해서 복화만 하면 되는것이다. SEED 구현 + CBC 운용모드 구현을 직접하려면 정신적인 데미지가 커질 수 있으므로, 만들어놓은것을 가져다 쓰겠다.
Bouncy Castle Crypto APIs(http://www.bouncycastle.org/)를 감사하는 마음으로 가져다 쓰자.
%JAVA_HOME%/jre/lib/ext에 해당 jar파일을 복사한 다음, %JAVA_HOME%/jre/lib/security/java.security 파일에
security.provider.7=org.bouncycastle.jce.provider.BouncyCastleProvider
을 추가해서 사용할 수 있지만, 귀찮은 관계로 그냥(?) 사용하겠다.
		// 3. SEED로 복호화하기
		BouncyCastleProvider provider = new BouncyCastleProvider();
		Cipher cipher = Cipher.getInstance("SEED/CBC/PKCS5Padding", provider);
		Key key = new SecretKeySpec(keyData, "SEED");
		cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
		byte[] output = cipher.doFinal(encryptedPrivateKeyInfo.getEncryptedData());

이젠 해당 데이터로 개인키를 생성만 해주면 된다.
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(output);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey)keyFactory.generatePrivate(keySpec);
		System.out.println(privateKey);
 패스워드를 일치여부는 PBES에서 정의한 패딩이 존재하는지 여부로 판단한다. 만약 잘못된 패스워드라면
Exception in thread "main" javax.crypto.BadPaddingException: pad block corrupted
같은 에러가 발생할것이다.


그럼 마지막으로 공인인증서의 공개키와 개인키를 가지고 어제 해본 전자서명을 한번 해보자.
package test.security;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.spec.PKCS8EncodedKeySpec;
 
import javax.crypto.Cipher;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
 
import kr.kangwoo.util.ByteUtils;
 
import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
import com.jarusoft.util.security.SHA1Utils;
 
public class CertificateTest {
	
	public static void main(String[] args) throws Exception {
		String msg = "하늘에는 달이 없고, 땅에는 바람이 없습니다.\n사람들은 소리가 없고, 나는 마음이 없습니다.\n\n우주는 죽음인가요.\n인생은 잠인가요.";
		PublicKey publicKey = getPublicKey("C:/signCert.der");
		PrivateKey privateKey = getPrivateKey("C:/signPri.key");
 
		// 전자서명하기
		Signature signatureA = Signature.getInstance("SHA1withRSA");
		signatureA.initSign(privateKey);
		signatureA.update(msg.getBytes());
		byte[] sign = signatureA.sign();
		System.out.println("signature : " + ByteUtils.toHexString(sign));
		
		// 전사서명 검증하기
		String msgB = msg;
		Signature signatureB = Signature.getInstance("SHA1withRSA");
		signatureB.initVerify(publicKey);
		signatureB.update(msgB.getBytes());
		boolean verifty = signatureB.verify(sign);
		System.out.println("검증 결과 : " + verifty);
	}
	
	public static PublicKey getPublicKey(String file) throws Exception {
		X509Certificate cert = null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(new File(file));
			CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
			cert = (X509Certificate) certificateFactory.generateCertificate(fis);
		} finally {
			if (fis != null) try {fis.close();} catch(IOException ie) {}
		}
		System.out.println(cert.getPublicKey());
		return cert.getPublicKey();
	}
 
	public static PrivateKey getPrivateKey(String file) throws Exception {
		// 1. 개인키 파일 읽어오기
		byte[] encodedKey = null;
		FileInputStream fis = null;
		ByteArrayOutputStream bos = null;
		try {
			fis = new FileInputStream(new File(file));
			bos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int read = -1;
			while ((read = fis.read(buffer)) != -1) {
				bos.write(buffer, 0, read);
			}
			encodedKey = bos.toByteArray();
		} finally {
			if (bos != null) try {bos.close();} catch(IOException ie) {}
			if (fis != null) try {fis.close();} catch(IOException ie) {}
		}
 
		System.out.println("EncodedKey : " + ByteUtils.toHexString(encodedKey));
		
		// 2. 개인카 파일 분석하기
		EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(encodedKey);
		System.out.println(encryptedPrivateKeyInfo);
		System.out.println(encryptedPrivateKeyInfo.getAlgName());
		
		byte[] salt = new byte[8];
		System.arraycopy(encodedKey, 20, salt, 0, 8);
		System.out.println("salt : " + ByteUtils.toHexString(salt));
		byte[] cBytes = new byte[4];
		System.arraycopy(encodedKey, 30, cBytes, 2, 2);
		int iterationCount = ByteUtils.toInt(cBytes);
		System.out.println("iterationCount : " + ByteUtils.toHexString(cBytes));
		System.out.println("iterationCount : " + iterationCount);
 
		
		String password = "password";
 
		// 추출키(DK) 생성
		byte[] dk = pbkdf1(password, salt, iterationCount);
		System.out.println("dk : " + ByteUtils.toHexString(dk));
		
		// 생성된 추출키(DK)에서 처음 16바이트를 암호화 키(K)로 정의한다.
		byte[] keyData = new byte[16];
		System.arraycopy(dk, 0, keyData, 0, 16);
		
	    // 추출키(DK)에서 암호화 키(K)를 제외한 나머지 4바이트를 SHA-1
	    // 으로 해쉬하여 20바이트의 값(DIV)을 생성하고,  그 중 처음 16바이트를 초기 
	    // 벡터(IV)로 정의한다.
		byte[] div = new byte[20];
		byte[] tmp4Bytes = new byte[4];
		System.arraycopy(dk, 16, tmp4Bytes, 0, 4);
		div = SHA1Utils.getHash(tmp4Bytes);
		System.out.println("div : " + ByteUtils.toHexString(div));
		byte[] iv = new byte[16];
		System.arraycopy(div, 0, iv, 0, 16);
		System.out.println("iv : " + ByteUtils.toHexString(iv));
 
		// 3. SEED로 복호화하기
		BouncyCastleProvider provider = new BouncyCastleProvider();
		Cipher cipher = Cipher.getInstance("SEED/CBC/PKCS5Padding", provider);
		Key key = new SecretKeySpec(keyData, "SEED");
		cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
		byte[] output = cipher.doFinal(encryptedPrivateKeyInfo.getEncryptedData());
 
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(output);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey)keyFactory.generatePrivate(keySpec);
		System.out.println(privateKey);
		return privateKey;
		
	}
 
	public static byte[] pbkdf1(String password, byte[] salt, int iterationCount) throws NoSuchAlgorithmException {
		byte[] dk = new byte[20]; // 생성이 의미가 없지만 한눈에 알아보라고 20바이트로 초기화
		MessageDigest md = MessageDigest.getInstance("SHA1");
		md.update(password.getBytes());
		md.update(salt);
		dk = md.digest();
		for (int i = 1; i < iterationCount; i++) {
			dk = md.digest(dk);
		}
		return dk;
	}
}



출처 : 剛宇님 블로그 (http://blog.kangwoo.kr/49)



'프로그래밍' 카테고리의 다른 글

RFC3852 - Cryptographic Message Syntax(CMS)  (0) 2009.07.30
공인인증서로 전자서명하기  (0) 2009.07.27
ASN.1  (1) 2009.07.27
[보안] RSA PKCS의 관련 자료  (0) 2009.03.09

태그

댓글 0

ASN.1

2009. 7. 27.

ASN.1은 CMIP, SNMP, X.400, X.500, EDI등 많은 Application에서 광범위 하게 사용되나 이에 대한 국내 웹 사이트의 정보가 전무하여 작은 경험이나마 공유하여 도움이 되고자 한다.

System간의 차이

Sun과 Windows간의 Data를 주고 받는 Application을 작성해본 사람들은 알겠지만 동일한 Data를 주고 받으면 Computer System에 따라 분석하는 것이 다르기 때문에 엉뚱한 값을 받게 된다.  예를 들어, 100이라는 값을 Sun에서 Windows 시스템으로 동일한 32 bit integer를 사용하여 보내면 Windows에서는 매우 큰 수로 인식하게 된다. (1,677,721,600) 이를 전문 용어로 Endian이라 하는데, Sun에서는 Motorola계열의 Big Endian을 사용하여 100을 [00 00 00 64]와 같이 인식한다.  이와는 반대로 Intel 진영인 Little Endian의 Windows에서는100을 [64 00 00 00]와 같이 인식한다.  따라서 어느 한쪽에서 Byte단위로 Swapping을 해주어야 한다.


이는 물론 Integer가 32 bit인 경우에 해당 되는 것이고 64-bit machine이나 8-bit, 16-bit인 경우에는 또 이야기가 달라진다.  Byte Alignment에 의해서 Structure의 구조를 주고 받을 때는 영향을 받으며 Compiler에 따라서 약간의 차이점 또한 생기게 된다.  이는 동일한 Language를 사용하는 경우며, 만약 C++와 Ada Application이 통신한다고 가정하면 그 문제는 더 더욱 복잡해 진다.

 

1 Conversion

System의 수가 늘어감에 따라 위와 같은 1대1의 Conversion 노력은 벽에 부닫치게 되었다.  왼쪽 그림에서 보는 것 과 같이 시스템간의 네트워크가 발전하면서 연동이 필요한 급증함을 알 수 있다.  6개의 장비가 있는 경우에 15가지의 Conversion이 개발 되어야 하며 각 시스템은 5개의 Conversion에 대한 노력을 기울여야 한다.  N 시스템이 있는 경우 각 Vendor는 N-1의 Conversion이 필요하게 된다.  이러 한계를 극복하기 위한 것이 ASN.1의 등장이다.  각 시스템에서는 ASN.1이라는 하나의 표준에 대한 Conversion만을 개발하면 모든 장비와 Data를 주고 받을 수 있게 된다.  멋지지 않는가.  이렇게 해서 만들어 진 것이 1988년 ITU ASN.1 규격이다. 



이렇게 해서 제정된 규격은 1990년, 1994년 그리고 1997에 Upgrade되어져 있으며 오늘날에 이르고 있다.  해당 규격은 아래와 같다.


버전

규격

제목

1988

X.208

Specification of Abstract Syntax Notation


X.209

Specification of Basic Encoding Rules for Abstract Notation One (ASN.1)



 

1990

ISO 8824

 


ISO 8825

 



 

1994

X.680

Specification of Basic Notation


X.681

Information Object Specification


X.682

Constraint Specification


X.683

Parameterization of ASN.1 Specification


X.690

ASN.1 Encoding Rules: Specification of Basic Encoding Rules, Canonical Encoding Rules, and Distinguished Encoding Rules


X.691

ASN.1 Encoding Rules: Specification of Packed Encoding Rules




1997

위와 동일

(1997년 버전)




TMN에서 사용되는 CMIP의 대부분의 규격은 ASN.1 1988년을 사용하고 있다.  1988년 버전은 초기 작품이라 Value 부분에 대한 부분은 parser를 개발 하기 거의 불가능하도록 되어 있는 등 많은 문제점을 안고 있다.  ASN.1 1997에서는 value Assignment에 대한 문제점을 포함한 많은 문제들이 해결되어 1988년에 비해 많이 사용 가능한 규격으로 생각된다.  1997년 버전에서는 Open Type의 개념이 소개 되는 대신 ANY type을 삭제하였다.  하지만, 이전의 규격이 ANY type을 많이 사용하기 때문에 1997년 버전에 ANY를 추가하여 사용하는 방법을 (비록 규격에는 위배되지만) Tool개발 업체에서 채택하는 것을 볼 수 있다.

자세한 내용은 Olivier Dubuisson의 책이나 ITU의 웹 사이트를 참조하길 바란다.

http://www.oss.com/asn1/dubuisson.html

http://www.itu.int/ITU-T/studygroups/com07/changing-ASN.html.



Abstract Syntax와 Transfer Syntax의 개념을 C와 비교하면 이해하기 매우 쉽다.  Abstract Syntax는 C에서 Type에 해당되는 것이다.  Transfer Syntax는 C에는 개념이 없으며 그 이유는 간단하다.  예를 들어 int i 라고 선언된 변수의 값을 저장하는 것은 C Compiler를 만드는 개발자에 자유게 맡긴다.  단지 i에 대한 연산을 하거나 화면에 보여주는 경우에 올바르게 보여주면 되는 것이다.  하지만 ASN.1의 경우에는 각 System간의 통신을 해야 하기 때문에 int i 의 값이 어떤 식으로 encoding이 되는지에 대한 규격이 필요하다.  이를 transfer syntax라고 하여 integer의 값은 어떻게 주고 받고, real값은 어떻게 주고 받는 등의 규약이 정해져 있다.  처음으로 돌아가서 C에서 굳이 Transfer Syntax의 개념과 유사한 것을 찾는다면 int i의 값이 저장되어 있는 형태라고 말할 수 있겠다.

Abstract Syntax는 사람을 위한 규격으로서 ITU문서에 적혀있는 것은 모두 Abstract Syntax를 사용한다.  (X.208, X.680~X.683).  이 ASN.1 규격을 사용하여 실제 값을 주고 받을 때 Transfer Syntax를 사용하게 되며 이에는 BER, PER, LWER 등이 있다. (X.208, X.690~1)

좀 더 실제적인 예제는 아래의 TLV Encoding 부분을 참조한다.


ASN.1을 공부하면서 헷갈리는 것이 있는데 그 중의 하나가 SEQUENCE와 SET이다.  SEQUENCE는 C의 struct와 동일한 개념이다.  SET의 개념은 C에는 없고, 굳이 찾는 다면 C의 struct에서 순서가 무의미한 type으로 보면 된다.


Seq ::= SEQUENCE {

  first INTEGER,

  second INTEGER

}


Set ::= SET {

first INTEGER,

  second INTEGER

}


seqVa1 Seq ::= { 10, 20 }

seqVal2 Seq ::= { 20, 10 }


setVal1 Set ::= { 10, 20 }

setVal2 Set ::= { 20, 10 }


seqVal1과 seqVal2의 경우에는 서로 다른 값이지만 setVal1과 setVal2는 동일한 값이다.



이 둘은 이름만 비슷하지 전혀 다는 개념이다.  SEQUENCE는 C의 struct이고 SEQUENCE OF는 C의 Array선언 [ ] 에 해당된다.


Name ::= SEQUENCE OF INTEGER는 int Name[ ] 과 동일한 의미이다.


SET과 SET OF도 유사하다.



SEQUENCE와 SET과 차이처럼 Array내 값의 순서가 의미를 가지느냐 여부의 차이이다.


SeqOf ::= SEQUENCE OF INTEGER

SetOf ::= SET OF INTEGER


seqOfVal1 SeqOf ::= { 10, 20, 30 }

seqOfVal2 SeqOf ::= { 20, 30, 10 }


setOfVal1 SeqOf ::= { 10, 20, 30 }

setOfVal2 SeqOf ::= { 20, 30, 10 }


seqOfVal1와 seqOfVal2는 다른 값이지만 setOfVal1와 setOfVal2는 동일한 값이다.



CHOICE는 C의 union과 동일한 개념이다.  CHOICE에 값을 선언할 때 선언되어 있는 Element중 하나를 사용하면 된다.


Choice ::= CHOICE {

  int INTEGER,

  string PrintableString

}


chocieVal1 Choice ::= int : 10

choiceVal2 Choice ::= string : “asn.1 is fun”


위의 예제는 1997년 ASN.1 표준을 따른 것이며 : 앞의 int와 string은 Choice의 Alternative의 identifier를 가리킨다.


 

송수신의 사용되는 Transfer Syntax은 TLV 형식을 취한다.  T는 Type이고, L은 Length 그리고 V는 Value이다.  Integer Type의 예를 들어보면 간단하다.


i ::= INTEGER 10


T

L

V

INTEGER

V 길이

10


실제 전송되는 값은 T L V에 해당된다.

T는 INTEGER에 해당하는 값으로 채워지게 된다.  Type에는 4가지의 Type이 있는데

자세한 내용은 나중에 생각하기로 하고 INTEGER에 대한 값이 들어간다고 만 생각하자.

Value는 Integer 10을 나타내는 값이 들어가고 L인 Length는 INTEGER i의 길이에 대한 정보를 담고 있게 된다.  주의해야 할 것은 i라는 정보는 전송되지 않는다는 점이다.  변수 이름인 i는 사람을 위한 것이다.

+Boolean이나 Enumerated와 같이 Simple한 Type의 경우에는 T L V 중 T의 값이 변하게 되지만, Sequence, Set, Choice와 같은 경우에는 다른 Simple Type을 포함하는 형태로 전송되어 진다.


Seq ::= SEQUENCE {

  first INTEGER,

  second INTEGER

}


seqVa1 Seq ::= { 10, 20 }


Seq의 경우에 T L V의 V부분에 SEQUENCE의 element에 해당되는 INTEGER인 first와 second의 내용이 TLV 형태로 들어가게 된다.

이를 그림으로 나타내면 아래와 같다.


T

L

V


SEQUENCE

V 길이*

T

L

V



INTEGER

V 길이

10



INTEGER

V 길이

20


SEQUENCE의 L 부분은 element인 first와 second의 길이 모두를 나타낸다.

TLV Encoding에서 제일 특이한 Type이 Choice인데 Choice에 해당하는 Type은 없다.  Choice는 alternative중에서 하나를 사용하기 때문에, 실제로 전송되는 값에는 선택된 alternative의 Type만으로 T L V의 형태를 띄게 된다.  Sequence의 Embedded Format과는 사뭇 다르게 된다.


재미 있는 경우를 보면, NULL Type이나 SEQUENCE OF, SET OF 그리고 Optional을 사용하는 경우, Length가 0인 경우도 발생한다는 사실이다.  결과적으로 T L(0) 만 나타나게 된다.



TAG은 Data를 상호간에 전송 시 Encoded data를 수신할 때 나타나는 문제점을 해결하기 위함이다.  간단한 예를 들어보면 쉽게 이해할 수 있다.  아래와 같은 SEQUENCE의 경우를 보자.


Seq ::= SEQUENCE {

  one INTEGER OPTIONAL,

  two INTEGER OPTIONAL

}


seqVal ::= Seq { one 10 }


위의 값이 Encoding 되면 T(SEQ) L T(INTEGER) L V(10)으로 보내어진다.  허나 이를 수신하는 측에서는 T(INTEGER)가 one인지 two인지 알 수 있는 방법이 없게 된다.  이를 위해서 소개된 개념이 Tag이다.  이와 같이 수신측에서 decoding 할 수 없는 규격의 경우에는 아래와 같이 Tag 정보를 추가해 사용한다.


Seq ::= SEQUENCE {

  one [1] INTEGER OPTIONAL,

  two [2] INTEGER OPTIONAL

}


seqVal ::= Seq { one 10 }


위의 경우에는 T(SEQ) L T([1]) L V(10)처럼 3번째의 Tag정보가 INTEGER 대신 [1]의 정보가 보내어진다.  수신측에서는 [1]이 one을 의미하는 것을 알기 때문에 V(10)이 integer type이라는 것을 알 수 있으며, 결과적으로 decoding에 전혀 문제가 없게 된다.


이와 유사하게 Set과 Choice의 경우에도 Tag이 사용된다.


Seq ::= SEQUENCE {

  one [1] INTEGER OPTIONAL,

  two [2] INTEGER OPTIONAL

}


seqVal ::= Seq { one 10 }


Tag 설명 부분에서 위의 seqVal이 T(SEQ) L T([1]) L V(10)으로 encoding되어 진다고 하였는데 이는 IMPLICIT TAG인 경우에 해당한다.  Implicit이 의미하는 것은 [1]의 Tag정보만으로 실제의 type을 알 수 있기 때문에 굳이 실제의 Type을 사용하지 않는다는 것으로 의미한다.

이와는 달리 Tag의 정보를 사용하고 실제 Type의 정보 또한 보내도록 하는 Option을 사용할 수 있다.  이를 EXPLICIT TAG이라고 하고 이 경우에는 encoding이 아래와 같이 되어진다.


T(SEQ) L T([1]) L T(INTEGER) V(10)


예상한대로 IMPLICIT TAG와 EXPLICIT TAG을 사용하는 규격간에는 동일한 값이라도 encoding이 다르게 된다는 것을 인식해야 한다.


AUTOMATIC TAG은 1997년에 소개된 개념으로써 위와 같은 경우에 일일이 수작업으로 규격에 TAG을 붙이는 것이 귀찮기 때문에 자동적으로 Tag을 붙이는 기능이다.  ITU에서는 이 기능의 사용을 적극적으로 권하고 있지만 TMN 규격들이 이전에 선언되었기 때문에 사용되는 일은 거의 없다.



동일한 ASN.1 규격의 사용

ASN.1 규격은 두개 이상의 Node가 정보를 주고 받기 위하여 만들어 진 것이다.  ASN.1 규격이란 이 정보가 어떤 형태를 가지는 것을 적어 놓은 것이다.  따라서 ASN.1 규격은 통신을 하는 모든 Node가 동일한 혹은 Compatible한 ASN.1 규격을 가지고 있어야 한다.



ASN.1 규격을 직접 만들거나, 정해진 ASN.1 규격을 구현을 위해 사용하는 경우에, 사용하는 Tool의 제한 사항 등으로 인해 나름대로의 수정이 필요하게 된다.  이때 고민하게 되는 것이 수정된 ASN.1 규격이 과연 기존의 ASN.1 규격과 통신 시 문제를 발생시키지 않을까 하는 걱정이 생기게 된다.


이름은 사람을 위한 것

ASN.1 규격상 모든 이름은 사람을 위한 것이다.  예를 들어, i ::= INTEGER 10에서 i란 이름은 사람을 위한 것이기 때문에 해당규격에서 모든 i를 newname으로 바꾸어도 상관없다.


Defined Type과 직접 사용

아래의 예제와 같이 INTEGER를 직접 사용하던지, Integer란 Type을 define하여 사용하던지 이는 동일하다.  Element가 Sequence나 Set의 경우에도 동일하게 적용된다.


Seq ::= SEQUENCE {

  one INTEGER,

  two INTEGER

}


Integer ::= INTEGER

Seq ::= SEQUENCE {

  one Integer,

  two INTEGER

}



사용하지 않는 규격의 가지치기

Workstation이나 Windows의 환경에서는 메모리에 대한 제한이 거의 없지만 Embedded 환경에서 ASN.1관련 작업을 하는 경우에는 메모리에 대한 부담을 가지게 된다.  이런 경우에는 ASN.1 규격상에서 절대로 사용하지 않는 부분을 제게 하는 것을 고려해 봄 직하다.  하지만, ASN.1 규격이라는 것이 모두 연결되어 있기 때문에 제거하는 것이 쉽지는 않다.


Select ::= CHOICE {

  this SomeSequence,

  that SomeSequence,

  never SequenceNeverUsed

}


never가 구현하는 application에서 사용하지 않는다는 것을 확신할 수 있으면 SequenceNeverUsed의 type선언과 여기서 파생되는 사용하지 않는 선언을 모두 삭제할 수 있다.  사용하지 않더라고 그대로 사용하면 parsing에 필요한 code들이 생성되기 때문에 그 만큼의 ROM을 필요로 하기 때문이다.

만약, 실제 상황에서 제거된 element가 수신되는 경우에는 어떤 일이 발생할까 ?  간단하다.  수신 측에서 분석이 불가능하다는 Parsing error가 발생하게 된다.



동일한 Defined Type의 통합

아래와 같이 동일한 definition이나 다른 이름을 사용하는 경우가 간혹 있다.  이는 가지치기를 한 후에 더 많이 생겨날 수 있는 가능성이 있는데 이 경우에 하나의 type으로 통일하여주면 formating과 parsing에 필요한 code들을 줄일 수 있다.


Select ::= CHOICE {

  this ThisSequence,

  that ThatSequence

}


ThisSequence ::= SEQUENCE {

  one INTEGER,

  two INTEGER

}


ThatSequence ::= SEQUENCE {

  one INTEGER,

  two INTEGER

}


위의 Choice는 아래와 같이 바꿀 수 있다.


Select ::= CHOICE {

  this ThisSequence,

  that ThisSequence

}



통신을 하기 위해서는 주어진 규격에 맞추어 값을 채우고 이를 ASN.1 Transfer Syntax에 맞는 형태의 byte stream을 만들어 주어야 한다.  그래야 PDU 형태로 송신을 할 수 있기 때문이다.  ASN.1 Compiler는 사용자의 ASN.1 규격을 읽어드려, 이에 대한 Validity를 확인하고, header file과 두 가지 종류의 c file을 만들어 낸다 - Formatter & Parser.  Header file은 사용자가 해당 type을 선언하여 사용할 때 사용하고 Formatter는 사용자의 값을 bit stream으로 바꾸어 주는 역할을 한다.  Parser는 이와 반대로 bit stream을 header file의 structure값으로 변환 시켜주는 기능을 수행한다.

이해를 위해 예를 들어 본다.  이는 특정 ASN.1 Compiler에 해당되는 내용이 아니며, ASN.1 Compiler마다 처리 방법은 각각 다르게 나타난다.


Seq ::= SEQUENCE {

  first INTEGER,

  second INTEGER

}


seqVa1 Seq ::= { 10, 20 }


[ Header File ]

"asn1header.h"


struct Seq {

  int first;

  int second;

}


사용자는 위의 header을 읽어드려서 송신을 위한 아래의 ASN.1 값을 만들게 된다.

[ 사용자 Code ]

#include "asn1header.h"


struct Seq asn1value = { 10, 20 };


이를 송신하기 위해서 ASN.1 Value를 bit stream으로 바꾸게 된다.

생성된 c code를 살펴보면 ASN.1의 각 type마다 formatter/parser가 생성됨을 알 수 있다.

사용되는 interface는 아래와 같다.


/* returns length */

int format_Seq(struct Seq *value; char *bitStream);

사용자는 준비된 asn1value를 formatter에 넣어주면 bitStream에 ASN.1 encoded가 생성되고 그 길이가 return되어진다.  Encoding되어진 값은 LAN과 같은 통신 채널을 통해 상대편 Node에 전해진다.


ASN.1 Encoded 값을 수신 받으면 아래의 parser를 이용하여 program에서 사용 가능한 structure의 형태로 바꾸게 된다.


Parser_Seq(char *bitStream, int len, struct Seq *value);


실제의 ASN.1 header, formatter, parser는 당연히 이보다 훨씬 더 복잡하게 되어 있다.  위의 예제는 ASN.1 Compiler에서 사용되는 개념만을 전달하기 위한 것으로, 이해를 위해서 최대한 단순화 시킨 것이다.


Object Identifier는 이름 그대로 OSI에서 사용되고 있는 Object를 나타내기 위한 ID이다.

Object Identifier는 { 2 9 3 5 2 0 }과 같이 생겼으며 아래와 같이 이름이나 이름과 숫자를 혼용하

여 사용되어 진다.  { joint-itu-ccitt ms(9) smi(3) asn1Module(2) attributes(0) }

ASN.1에는 OBJECT IDENTIFIER type이 지원된다.



Object Identifier는 Tree구조로 되어 있다.  가끔씩 ASN.1 규격을 보다 보면 번호

만 있는 경우가 있다.  이 번호가 어떤 object를 알고 싶은 경우가 있다.  하지만

이것이 만만한 일이 아니다.  규격을 다 검색할 수 도 없고… 이러한 경우, 찾고

자 하는 Object ID를 아래의 Site에 찾아 볼 수 있다.  Object Identifier Tree의 형

태가 궁금한 경우에도 Top에서 재미 삼아 보는 것도 도움이 될 듯 싶다.


http://asn1.elibel.tm.fr/en/oid/index.htm

http://www.alvestrand.no/objectid/top.html



ANY Type, EXTERNAL Type, SubType, Macro, 그리고 Object, Parameter 개념

등을 포함하여 많은 내용이 설명되어 있지 않다.  ASN.1에 대한 이해에 도움이

되자는 취지이기에 당연한 것일지도 모르겠다.  위의 개념을 포함한 모든 ASN.1

개념을 이해하는 것은 상당한 노력이 필요하다.  관심이 있는 분들은 아래의

Reference를 참조하기 바란다.



ASN.1 - Communication between heterogeneous systems

http://www.oss.com/asn1/dubuisson.html

현 ITU ASN.1 Project 리더로서 활동하고 있는 French Telecom의 Olivier

Dubuisson의 저서로써 무료로 배포하는 책이지만 지금까지 접한 책 중에 ASN.1에 관해 가장 상세하게 설명되어 있는 책이다.  많은 예제가 포함되어 ASN.1의 실제 사용에 대한 감각을 쉽게 얻을 수 있을 것으로 예상된다.  강력히 추천한다.


ASN.1 Complete

http://www.oss.com/asn1/larmouth.html

ASN.1에 dedicate되어 있는 또 하나의 책으로써 마찬가지로 무료로 배포되어 진다.



http://asn1.elibel.tm.fr/

http://www-sop.inria.fr/rodeo/personnel/hoschka/asn1.html

http://www.oss.com/asn1/




ASN.1 규격을 가지고 작업하다 보면 IMPORT된 type reference나 value reference를 찾는데 애를 먹게 되는 경우가 있다.  만약 ITU 규격에 선언되어 있는 것이라면 ITU ASN.1 Module Database를 사용하면 쉽게 찾을 수 있다.

또한 ASN.1 Definition이 필요한 경우 ITU규격에서 긁어와 사용해야 하는데 불편하다. 가끔씩 오류도 있고.  요즘에는 일반적으로 많이 사용되는 ASN.1 definition의 경우에는 Tool Vendor에서 제공되나, 부족한 경우에는 이곳에서 필요한 ASN.1 Definition을 가져 다 사용하면 수정 없이 그대로 사용 가능하다.


http://www.itu.int/ITU-T/asn1/database/index.html

http://www.itu.int/ITU-T/asn1/   Search 사용



<자료 출처: http://www.nexto.co.kr/tmn/asn1.htm>

'프로그래밍' 카테고리의 다른 글

공인인증서로 전자서명하기  (0) 2009.07.27
ASN.1  (1) 2009.07.27
[보안] RSA PKCS의 관련 자료  (0) 2009.03.09
[Java] HttpClient 간단 사용법 (@ 특정 IP 사용)  (0) 2009.03.03

태그

댓글 1
  • 니니야 2015.01.27 09:12 댓글주소 수정/삭제 댓글쓰기

    ASN.1 에 대해 제가 찾고 싶은 정보를 겨~~우 찾았네요!!
    포스팅 감사해서 댓글 달고 갑니다~~~^____^
    번창하세요~!!

손금.

2009. 6. 11.



- 손금 결과 -

결과를 보시기에 앞서서, "내 손금은 좋네", "왜 내 손금은 이렇지? 별로 않좋네..." 라는 등의 생각은 안하셔도 됩니다. 사람의 손금은 오늘, 내일이 멀다하며 계속 변화 하기 때문입니다. 손금은 누군가가 나에게 정해놓은 운명이 아니라, 나의 이상과 주관으로 만들어낸 지금 나의 상태를 말합니다. 

만약 손금에 좋지 않은 특징이 나타나면, 그에 대한 경고로 받아들이셔야 하며, 그 시기가 지나가면 자연스럽게 그 좋지 않았던 특징은 손금에서 없어집니다.

부디 현명한 대처를 하셔서 행복한 하루하루가 되시기를 바랍니다.




건강 상태


- 전체적으로 생명 에너지가 넘치는 상태이며, 활기차고 병과 사고에 강한 저항력을 가지고 있습니다.
- 생명선의 흔들림으로 인하여, 체질이 약하게 된 상태이며 쉽게 신경이 예민해 집니다.
- 현재는 대체적으로 무난한 건강상태를 가지고 있습니다.



애정과 감성

- 애정에 대하여 정열적이지만 감정의 기복이 심한 편 입니다.
- 감성이 풍부하여 매력적이지만, 변덕이 심하여 자기중심적인 성향이 강합니다.
- 한쪽에 치우치지 않는 무난한 타입의 애정관을 가졌습니다.
- 가정적이며 배우자에게 양보할줄 아는 따듯한 애정성향을 가지고 있습니다.
- 현재는 별다른 문제점은 있지 않은 상태 입니다.



두뇌회전

- 많은것에 능통하기보다는 몇가지의 것에 해박한 특징을 가지고 있습니다.
- 단순하거나 평범하지 않은 복잡한 정신구조를 가지고 있습니다.
- 감수성이 풍부하고 낭만적이며 예술에 대한 재능이 있지만, 공상에 빠지기 쉽고 소심한 성향을 가지고 있습니다.
- 두뇌회전도 적당하며 일의 처리에 있어서도 무난한 성격을 두루 가지고 있습니다.
- 업무처리와 처세술에 있어서 원만한 능력과 성격을 가지고 있습니다.



삶의주관과 성공가능성

- 생활하면서 주위환경의 변동이 자주 일어날 수 있으며, 주위 환경에 대한 적응력이 약해져 있는 상태 입니다. 더욱 강한 결단이 필요한 때 입니다.
- 주체성이 약하며 확실한 삶의주관이 부족한 상태 입니다. 심신의 수련이 필요 합니다.
- 다른 지원없이, 독립적으로 본인의 노력으로 성공할 가능성이 높은 사람 입니다.
- 현재 별다른 문제 없이 무난한 상태 입니다.
- 커다란 문제 없이 인생을 진행하고 있는 상태 입니다.
- 현재는 별다른 문제가 없습니다.



----------------------------------------------------------------------------------

특별한 무언가를 기대했건만..
전부 다 그냥 무난하군.. ㅠㅠ


손금 보러 가기~






'끄적끄적' 카테고리의 다른 글

마우스 지름  (0) 2009.09.22
손금.  (0) 2009.06.11
오랫만에~  (2) 2008.12.09
Spinn + Triple.fi 10 pro  (0) 2008.10.04

태그

댓글 0

(100일 완성) 묻지마 맞춤법

2009. 6. 2.



서문 http://blog.naver.com/uvz/40051363956


01일 http://blog.naver.com/uvz/40051391516
02일 http://blog.naver.com/uvz/40051424268
03일 http://blog.naver.com/uvz/40051455339
04일 http://blog.naver.com/uvz/40051502101
05일 http://blog.naver.com/uvz/40051543896
06일 http://blog.naver.com/uvz/40051574838
07일 http://blog.naver.com/uvz/40051606440
08일 http://blog.naver.com/uvz/40051634536
09일 http://blog.naver.com/uvz/40051666033
10일 http://blog.naver.com/uvz/40051707674


11일 http://blog.naver.com/uvz/40051969743
12일 http://blog.naver.com/uvz/40052000931
13일 http://blog.naver.com/uvz/40052035455
14일 http://blog.naver.com/uvz/40052066901
15일 http://blog.naver.com/uvz/40052097255
16일 http://blog.naver.com/uvz/40052125134
17일 http://blog.naver.com/uvz/40052157443
18일 http://blog.naver.com/uvz/40052191587
19일 http://blog.naver.com/uvz/40052222502
20일 http://blog.naver.com/uvz/40052251225


21일 http://blog.naver.com/uvz/40052285451
22일 http://blog.naver.com/uvz/40052319091
23일 http://blog.naver.com/uvz/40052351700
24일 http://blog.naver.com/uvz/40052384049
25일 http://blog.naver.com/uvz/40052412700
26일 http://blog.naver.com/uvz/40052442762
27일 http://blog.naver.com/uvz/40052473866
28일 http://blog.naver.com/uvz/40052504202
29일 http://blog.naver.com/uvz/40052535302
30일 http://blog.naver.com/uvz/40052564323


31일 http://blog.naver.com/uvz/40052593857
32일 http://blog.naver.com/uvz/40052619533
33일 http://blog.naver.com/uvz/40052650806
34일 http://blog.naver.com/uvz/40052678594
35일 http://blog.naver.com/uvz/40052705069
36일 http://blog.naver.com/uvz/40052733365
37일 http://blog.naver.com/uvz/40052761992
38일 http://blog.naver.com/uvz/40052789305
39일 http://blog.naver.com/uvz/40052815053
40일 http://blog.naver.com/uvz/40052843146


41일 http://blog.naver.com/uvz/40052872835
42일 http://blog.naver.com/uvz/40052902968
43일 http://blog.naver.com/uvz/40052929913
44일 http://blog.naver.com/uvz/40052958259
45일 http://blog.naver.com/uvz/40052990266
46일 http://blog.naver.com/uvz/40053019295
47일 http://blog.naver.com/uvz/40053048526
48일 http://blog.naver.com/uvz/40053079455
49일 http://blog.naver.com/uvz/40053109590
50일 http://blog.naver.com/uvz/40053139589


51일 http://blog.naver.com/uvz/40053170204
52일 http://blog.naver.com/uvz/40053201726
53일 http://blog.naver.com/uvz/40053232879
54일 http://blog.naver.com/uvz/40053264891
55일 http://blog.naver.com/uvz/40053297235
56일 http://blog.naver.com/uvz/40053330548
57일 http://blog.naver.com/uvz/40053365962
58일 http://blog.naver.com/uvz/40053402859
59일 http://blog.naver.com/uvz/40053433622
60일 http://blog.naver.com/uvz/40053462502


61일 http://blog.naver.com/uvz/40053498218
62일 http://blog.naver.com/uvz/40053530862
63일 http://blog.naver.com/uvz/40053565362
64일 http://blog.naver.com/uvz/40053578873
65일 http://blog.naver.com/uvz/40053611150
66일 http://blog.naver.com/uvz/40053625783
67일 http://blog.naver.com/uvz/40053631191
68일 http://blog.naver.com/uvz/40053659059
69일 http://blog.naver.com/uvz/40053686138
70일 http://blog.naver.com/uvz/40053716398


71일 http://blog.naver.com/uvz/40053726412
72일 http://blog.naver.com/uvz/40053726695
73일 http://blog.naver.com/uvz/40053744658
74일 http://blog.naver.com/uvz/40053748872
75일 http://blog.naver.com/uvz/40053780560
76일 http://blog.naver.com/uvz/40053803996
77일 http://blog.naver.com/uvz/40053815632
78일 http://blog.naver.com/uvz/40053815849
79일 http://blog.naver.com/uvz/40053845646
80일 http://blog.naver.com/uvz/40053846739


81일 http://blog.naver.com/uvz/40053899111
82일 http://blog.naver.com/uvz/40053899175
83일 http://blog.naver.com/uvz/40053899239
84일 http://blog.naver.com/uvz/40053930680
85일 http://blog.naver.com/uvz/40053963147
86일 http://blog.naver.com/uvz/40054028395
87일 http://blog.naver.com/uvz/40054028481
88일 http://blog.naver.com/uvz/40054119443
89일 http://blog.naver.com/uvz/40054119604
90일 http://blog.naver.com/uvz/40054157294


91일 http://blog.naver.com/uvz/40054189640
92일 http://blog.naver.com/uvz/40054195010
93일 http://blog.naver.com/uvz/40054221221
94일 http://blog.naver.com/uvz/40054221607
95일 http://blog.naver.com/uvz/40054256494
96일 http://blog.naver.com/uvz/40054264372
97일 http://blog.naver.com/uvz/40054264419
98일 http://blog.naver.com/uvz/40054283701
99일 http://blog.naver.com/uvz/40054286779
00일 http://blog.naver.com/uvz/40054299803



태그

댓글 0