LibItsSecurity_Functions.ttcn 194 KB
Newer Older
garciay's avatar
garciay committed
/**
 *  @author   ETSI / STF481 / STF507 / STF517 / STF538 / STF545
garciay's avatar
garciay committed
 *  @version  $URL$
 *            $Id$
 *  @desc     Module containing functions for Security Protocol
garciay's avatar
garciay committed
 *  @copyright   ETSI Copyright Notification
 *               No part may be reproduced except as authorized by written permission.
 *               The copyright and the foregoing restriction extend to reproduction in all media.
 *               All rights reserved.
garciay's avatar
garciay committed
 *
 */
module LibItsSecurity_Functions {
    import from LibCommon_BasicTypesAndValues all;
    // LibIts
    import from IEEE1609dot2BaseTypes language "ASN.1:1997" all;
    import from IEEE1609dot2 language "ASN.1:1997" all;
    import from EtsiTs103097Module language "ASN.1:1997" all;
    
filatov's avatar
filatov committed
    //import from LibItsCommon_Functions all;
    //import from LibItsCommon_TypesAndValues all;
    
    // LibItsSecurity
    import from LibItsSecurity_TypesAndValues all;
    import from LibItsSecurity_Templates all;
    import from LibItsSecurity_Pixits all;
garciay's avatar
garciay committed
    import from LibItsSecurity_Pics all;
    import from LibItsSecurity_TestSystem all;
garciay's avatar
garciay committed
    
    group helpersFunctions {
garciay's avatar
garciay committed
         * @desc    Produces a 256-bit (32-byte) hash value
         * @param   p_toBeHashedData Data to be used to calculate the hash value
         * @return  The hash value
         */
garciay's avatar
garciay committed
                                  in octetstring p_toBeHashedData
            return fx_hashWithSha256(p_toBeHashedData);
        } // End of function f_hashWithSha256
garciay's avatar
garciay committed
         * @desc    Produces a 384-bit (48-byte) hash value
         * @param   p_toBeHashedData Data to be used to calculate the hash value
         * @return  The hash value
         */
        function f_hashWithSha384(
                                  in octetstring p_toBeHashedData
        ) return Oct48 {
            return fx_hashWithSha384(p_toBeHashedData);
        } // End of function f_hashWithSha256
        
        /**
Yann Garcia's avatar
Yann Garcia committed
         * @desc    Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature based on standard IEEE 1609.2
         * @param   p_toBeSignedSecuredMessage    The data to be signed
         * @param   p_certificateIssuer           The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
         * @param   p_privateKey                  The private key for signature
garciay's avatar
garciay committed
         * @return  The signature value
         */
        function f_signWithEcdsaNistp256WithSha256(
                                                   in octetstring p_toBeSignedSecuredMessage,
                                                   in Oct32 p_certificateIssuer,
        ) return octetstring {
            return fx_signWithEcdsaNistp256WithSha256(
                p_toBeSignedSecuredMessage,
        } // End of function f_signWithEcdsaNistp256WithSha256
garciay's avatar
garciay committed
        /**
Yann Garcia's avatar
Yann Garcia committed
         * @desc    Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature based on standard IEEE 1609.2
         * @param   p_toBeSignedSecuredMessage    The data to be signed
         * @param   p_certificateIssuer           The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
         * @param   p_privateKey                  The private key for signature
garciay's avatar
garciay committed
         * @return  The signature value
         */
        function f_signWithEcdsaBrainpoolp256WithSha256(
                                                        in octetstring p_toBeSignedSecuredMessage,
                                                        in Oct32 p_certificateIssuer,
garciay's avatar
garciay committed
                                                        in Oct32 p_privateKey
        ) return octetstring {
garciay's avatar
garciay committed
            return fx_signWithEcdsaBrainpoolp256WithSha256(
                p_toBeSignedSecuredMessage,
garciay's avatar
garciay committed
                p_privateKey
            );
            
        } // End of function f_signWithEcdsaBrainpoolp256WithSha256
        
garciay's avatar
garciay committed
        /**
Yann Garcia's avatar
Yann Garcia committed
         * @desc    Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature based on standard IEEE 1609.2
         * @param   p_toBeSignedSecuredMessage    The data to be signed
         * @param   p_certificateIssuer           The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
         * @param   p_privateKey                  The private key for signature
garciay's avatar
garciay committed
         * @return  The signature value
         */
        function f_signWithEcdsaBrainpoolp384WithSha384(
                                                        in octetstring p_toBeSignedSecuredMessage,
                                                        in Oct48 p_certificateIssuer,
garciay's avatar
garciay committed
                                                        in Oct48 p_privateKey
        ) return octetstring {
garciay's avatar
garciay committed
            return fx_signWithEcdsaBrainpoolp384WithSha384(
                p_toBeSignedSecuredMessage,
garciay's avatar
garciay committed
                p_privateKey
            );
            
        } // End of function f_signWithEcdsaBrainpoolp384WithSha384
        
        function f_decrypt(
                           in octetstring         p_encryptPrivateKey,
                           in EtsiTs103097Data    p_encrypedSecuredMessage,
Yann Garcia's avatar
Yann Garcia committed
                           out EtsiTs103097Data   p_decrypedSecuredMessage,
                           out octetstring        p_aes_sym_enc_key
        ) return boolean {
            if (ischosen(p_encrypedSecuredMessage.content.encryptedData)) {
                var PKRecipientInfo v_pKRecipientInfo;
                var RecipientInfo v_recipientInfo := p_encrypedSecuredMessage.content.encryptedData.recipients[0];
            var octetstring v_decryptedSecuredMessage;
                // Check the private encryption key
                if (not(isbound(p_encryptPrivateKey))) {
                  log("*** " & testcasename() & ":ERROR: Failed to load encryption private key ***");
                  return false;
                }
                
                if (ischosen(v_recipientInfo.certRecipInfo)) {
                  v_pKRecipientInfo := p_encrypedSecuredMessage.content.encryptedData.recipients[0].certRecipInfo;
                  // Read the certificate based on the recipientId
                } else if (ischosen(v_recipientInfo.signedDataRecipInfo)) {
                v_pKRecipientInfo := p_encrypedSecuredMessage.content.encryptedData.recipients[0].signedDataRecipInfo;
                  // Read the certificate based on the recipientId
                  log("*** " & testcasename() & ":ERROR: Unsupported RecipientInfo variant ***");
                  return false;
            if (isbound(v_pKRecipientInfo)) {
                if (ischosen(v_pKRecipientInfo.encKey.eciesNistP256)) {
                  var SymmetricCiphertext v_ciphertext := p_encrypedSecuredMessage.content.encryptedData.ciphertext;
                  if (ischosen(v_pKRecipientInfo.encKey.eciesNistP256.v.compressed_y_0)) {
                      v_decryptedSecuredMessage := f_decryptWithEciesNistp256WithSha256(
                                                                                        v_ciphertext.aes128ccm.ccmCiphertext,
                                                                                        p_encryptPrivateKey,
                                                                                        v_pKRecipientInfo.encKey.eciesNistP256.v.compressed_y_0,
                                                                                        0,
                                                                                        v_pKRecipientInfo.encKey.eciesNistP256.c,
                                                                                        v_pKRecipientInfo.encKey.eciesNistP256.t,
                                                                                        v_ciphertext.aes128ccm.nonce,
Yann Garcia's avatar
Yann Garcia committed
                                                                                        p_salt,
                                                                                        p_aes_sym_enc_key
                                                                                        );
                  } else if (ischosen(v_pKRecipientInfo.encKey.eciesNistP256.v.compressed_y_1)) {
                      v_decryptedSecuredMessage := f_decryptWithEciesNistp256WithSha256(
                                                                                        v_ciphertext.aes128ccm.ccmCiphertext,
                                                                                        p_encryptPrivateKey,
                                                                                        v_pKRecipientInfo.encKey.eciesNistP256.v.compressed_y_1,
                                                                                        1,
                                                                                        v_pKRecipientInfo.encKey.eciesNistP256.c,
                                                                                        v_pKRecipientInfo.encKey.eciesNistP256.t,
                                                                                        v_ciphertext.aes128ccm.nonce,
Yann Garcia's avatar
Yann Garcia committed
                                                                                        p_salt,
                                                                                        p_aes_sym_enc_key
                                                                                        );
                  } else {
                    log("*** " & testcasename() & ":ERROR: Non canonical ephemeral encryption keys ***");
                    return false;
                  }
                  if (isbound(v_decryptedSecuredMessage)) {
                    var bitstring v_decode := oct2bit(v_decryptedSecuredMessage);
                    if (decvalue(v_decode, p_decrypedSecuredMessage) == 0) {
                      return true;
                    } else {
                      log("*** " & testcasename() & ":ERROR: Faild to decode secured message ***");
                } else if (ischosen(v_pKRecipientInfo.encKey.eciesBrainpoolP256r1)) {
                  var SymmetricCiphertext v_ciphertext := p_encrypedSecuredMessage.content.encryptedData.ciphertext;
                  if (ischosen(v_pKRecipientInfo.encKey.eciesBrainpoolP256r1.v.compressed_y_0)) {
                    v_decryptedSecuredMessage := f_decryptWithEciesBrainpoolp256WithSha256(
                                                                                           v_ciphertext.aes128ccm.ccmCiphertext,
                                                                                           p_encryptPrivateKey,
                                                                                           v_pKRecipientInfo.encKey.eciesBrainpoolP256r1.v.compressed_y_0,
                                                                                           0,
                                                                                           v_pKRecipientInfo.encKey.eciesBrainpoolP256r1.c,
                                                                                           v_pKRecipientInfo.encKey.eciesBrainpoolP256r1.t,
Yann Garcia's avatar
Yann Garcia committed
                                                                                           v_ciphertext.aes128ccm.nonce,
                                                                                           p_salt,                                                                                                                                                     p_aes_sym_enc_key
                                                                                      );
                  } else if (ischosen(v_pKRecipientInfo.encKey.eciesBrainpoolP256r1.v.compressed_y_1)) {
                    v_decryptedSecuredMessage := f_decryptWithEciesBrainpoolp256WithSha256(
                                                                                           v_ciphertext.aes128ccm.ccmCiphertext,
                                                                                           p_encryptPrivateKey,
                                                                                           v_pKRecipientInfo.encKey.eciesBrainpoolP256r1.v.compressed_y_1,
                                                                                           1,
                                                                                           v_pKRecipientInfo.encKey.eciesBrainpoolP256r1.c,
                                                                                           v_pKRecipientInfo.encKey.eciesBrainpoolP256r1.t,
Yann Garcia's avatar
Yann Garcia committed
                                                                                           v_ciphertext.aes128ccm.nonce,
                                                                                           p_salt,
                                                                                           p_aes_sym_enc_key
                                                                                      );
                  } else {
                    log("*** " & testcasename() & ":ERROR: Non canonical ephemeral encryption keys ***");
                    return false;
                  }
              } else {
                log("*** " & testcasename() & ":ERROR: Non canonical ephemeral encryption keys ***");
                return false;
              }
              // TODO else, other variants shall be processed here if
            } else {
              log("*** " & testcasename() & ":ERROR: Invalid recipient info ***");
              return false;
            }
                  if (isbound(v_decryptedSecuredMessage)) {
                    var bitstring v_decode := oct2bit(v_decryptedSecuredMessage);
                    if (decvalue(v_decode, p_decrypedSecuredMessage) == 0) {
                      return true;
                    } else {
                      log("*** " & testcasename() & ":ERROR: Faild to decode secured message ***");
            } else {
              log("*** " & testcasename() & ":ERROR: Message not encrypted ***");
        } // End of function f_decrypt
         * @desc    Produces a Elliptic Curve Digital Encrytion Algorithm (ECIES) encryption using Nist-P256 algorithm
         * @param   p_toBeEncryptedSecuredMessage    The data to be encrypted
         * @param   p_recipientsPublicKeyCompressed  The Recipient's compressed public key
         * @param   p_compressed_mode                 The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
         * @param   p_publicEphemeralKeyCompressed   The generated ephemeral compressed key
         * @param   p_ephemeralKeyModeCompressed     The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
         * @param   p_encrypted_sym_key              The encrypted AES 128 CCM symmetric key
         * @param   p_authentication_vector          The tag of the AES 128 CCM symmetric key encryption
         * @param   p_nonce                          The nonce vector of the AES 128 CCM symmetric key encryption
         * @see IEEE Std 1609.2-2017 Clause 5.3.5 Public key encryption algorithms: ECIES
         * @see https://www.nominet.uk/researchblog/how-elliptic-curve-cryptography-encryption-works/
         * @see http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf
         * @return  The encrypted message
         */
        function f_encryptWithEciesNistp256WithSha256(
                                                      in octetstring p_toBeEncryptedSecuredMessage,
                                                      in Oct32 p_recipientsPublicKeyCompressed,
                                                      in integer p_compressed_mode,
                                                      out Oct32 p_publicEphemeralKeyCompressed,
                                                      out integer p_ephemeralKeyModeCompressed,
                                                      out Oct16 p_aes_sym_key,
                                                      out Oct16 p_encrypted_sym_key,
                                                      out Oct16 p_authentication_vector,
                                                      out Oct12 p_nonce,
                                                      in boolean p_use_hardcoded_values := false
        ) return octetstring {
          return fx_encryptWithEciesNistp256WithSha256(
                                                       p_toBeEncryptedSecuredMessage,
                                                       p_recipientsPublicKeyCompressed,
                                                       p_compressed_mode,
                                                       p_publicEphemeralKeyCompressed,
                                                       p_ephemeralKeyModeCompressed,
                                                       p_aes_sym_key,
                                                       p_encrypted_sym_key,
                                                       p_authentication_vector,
                                                       p_nonce,
                                                       p_use_hardcoded_values
        } // End of function f_encryptWithEciesNistp256WithSha256
        
        /**
         * @desc    Produces a Elliptic Curve Digital Encrytion Algorithm (ECIES) decryption using Nist-P256 algorithm
         * @param   p_encryptedSecuredMessage    The data to be decrypted
         * @param   p_publicEphemeralKeyCompressed   The generated ephemeral compressed key
         * @param   p_ephemeralKeyModeCompressed     The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
         * @param   p_encrypted_sym_key              The encrypted AES 128 CCM symmetric key
         * @param   p_authentication_vector          The tag of the AES 128 CCM symmetric key encryption
         * @param   p_nonce                          The nonce vector of the AES 128 CCM symmetric key encryption
         * @return  The decrypted message
         * @see IEEE Std 1609.2-2017 Clause 5.3.5 Public key encryption algorithms: ECIES
         * @see https://www.nominet.uk/researchblog/how-elliptic-curve-cryptography-encryption-works/
         * @see http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf
         */
        function f_decryptWithEciesNistp256WithSha256(
                                                      in octetstring p_encryptedSecuredMessage,
                                                      in Oct32 p_privateEncKey,
                                                      in Oct32 p_publicEphemeralKeyCompressed,
                                                      in integer p_ephemeralKeyModeCompressed,
                                                      in Oct16 p_encrypted_sym_key,
                                                      in Oct16 p_authentication_vector,
Yann Garcia's avatar
Yann Garcia committed
                                                      in Oct32 p_salt,
                                                      out Oct16 p_aes_sym_enc_key
        ) return octetstring {
          return fx_decryptWithEciesNistp256WithSha256(
                                                       p_encryptedSecuredMessage,
                                                       p_privateEncKey,
                                                       p_publicEphemeralKeyCompressed, 
                                                       p_ephemeralKeyModeCompressed,
                                                       p_encrypted_sym_key,
                                                       p_authentication_vector,
Yann Garcia's avatar
Yann Garcia committed
                                                       p_salt,
                                                       p_aes_sym_enc_key
        } // End of function f_decryptWithEcdsaNistp256WithSha256
        
        /**
         * @desc    Produces a Elliptic Curve Digital Encrytion Algorithm (ECIES) encryption using Brainpool-P256 algorithm
         * @param   p_toBeEncryptedSecuredMessage    The data to be encrypted
         * @param   p_recipientsPublicKeyCompressed  The Recipient's compressed public key
         * @param   p_compressed_mode                 The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
         * @param   p_publicEphemeralKeyCompressed   The generated ephemeral compressed key
         * @param   p_ephemeralKeyModeCompressed     The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
         * @param   p_encrypted_sym_key              The encrypted AES 128 CCM symmetric key
         * @param   p_authentication_vector          The tag of the AES 128 CCM symmetric key encryption
         * @param   p_nonce                          The nonce vector of the AES 128 CCM symmetric key encryption
         * @return  The encrypted message
         * @see IEEE Std 1609.2-2017 Clause 5.3.5 Public key encryption algorithms: ECIES
         * @see https://www.nominet.uk/researchblog/how-elliptic-curve-cryptography-encryption-works/
         * @see http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf
         */
        function f_encryptWithEciesBrainpoolp256WithSha256(
                                                           in octetstring p_toBeEncryptedSecuredMessage,
                                                           in Oct32 p_recipientsPublicKeyCompressed,
                                                           in integer p_compressed_mode,
                                                           in octetstring p_salt,
                                                           out Oct32 p_publicEphemeralKeyCompressed,
                                                           out integer p_ephemeralKeyModeCompressed,
                                                           out Oct16 p_aes_sym_key,
                                                           out Oct16 p_encrypted_sym_key,
                                                           out Oct16 p_authentication_vector,
                                                           out Oct12 p_nonce,
                                                           in boolean p_use_hardcoded_values := false
        ) return octetstring {
          return fx_encryptWithEciesBrainpoolp256WithSha256(
                                                            p_toBeEncryptedSecuredMessage,
                                                            p_recipientsPublicKeyCompressed,
                                                            p_compressed_mode,
                                                            p_publicEphemeralKeyCompressed,
                                                            p_ephemeralKeyModeCompressed,
                                                            p_aes_sym_key,
                                                            p_encrypted_sym_key,
                                                            p_authentication_vector,
                                                            p_nonce,
                                                            p_use_hardcoded_values
        } // End of function f_encryptWithEciesBrainpoolp256WithSha256
        
        /**
         * @desc    Produces a Elliptic Curve Digital Encrytion Algorithm (ECIES) decryption using Brainpool-P256 algorithm
         * @param   p_encryptedSecuredMessage    The data to be decrypted
         * @param   p_publicEphemeralKeyCompressed   The generated ephemeral compressed key
         * @param   p_ephemeralKeyModeCompressed     The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
         * @param   p_encrypted_sym_key              The encrypted AES 128 CCM symmetric key
         * @param   p_authentication_vector          The tag of the AES 128 CCM symmetric key encryption
         * @param   p_nonce                          The nonce vector of the AES 128 CCM symmetric key encryption
         * @return  The decrypted message
         * @see IEEE Std 1609.2-2017 Clause 5.3.5 Public key encryption algorithms: ECIES
         * @see https://www.nominet.uk/researchblog/how-elliptic-curve-cryptography-encryption-works/
         * @see http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf
         */
        function f_decryptWithEciesBrainpoolp256WithSha256(
                                                           in octetstring p_encryptedSecuredMessage,
                                                           in Oct32 p_privateEncKey,
                                                           in Oct32 p_publicEphemeralKeyCompressed, 
                                                           in integer p_ephemeralKeyModeCompressed,
                                                           in Oct16 p_encrypted_sym_key,
                                                           in Oct16 p_authentication_vector,
Yann Garcia's avatar
Yann Garcia committed
                                                           in Oct12 p_nonce,
                                                           in Oct32 p_salt,
                                                           out Oct16 p_aes_sym_enc_key
        ) return octetstring {
          return fx_decryptWithEciesBrainpoolp256WithSha256(
                                                            p_encryptedSecuredMessage,
                                                            p_privateEncKey,
                                                            p_publicEphemeralKeyCompressed, 
                                                            p_ephemeralKeyModeCompressed,
                                                            p_encrypted_sym_key,
                                                            p_authentication_vector,
Yann Garcia's avatar
Yann Garcia committed
                                                            p_nonce,
                                                            p_salt,
                                                            p_aes_sym_enc_key
        } // End of function f_decryptWithEcdsaBrainpoolp256WithSha256
        
garciay's avatar
garciay committed
         * @desc Compute the HashedId8 value from the hash value
         * @param p_hash The hash value
         * @return The HashedId8 value
         * @verdict
         */
        function f_HashedId8FromSha256( 
garciay's avatar
garciay committed
                                       in Oct32 p_hash
        ) return HashedId8 {
            return substr(p_hash, lengthof(p_hash) - 8, 8);
        } // End of function f_HashedId8FromSha256
        /**
         * @desc Compute the HashedId8 value from the hash value
         * @param p_hash The hash value
         * @return The HashedId8 value
         * @verdict
         */
        function f_HashedId8FromSha384( 
                                       in Oct48 p_hash
        ) return HashedId8 {
            return substr(p_hash, lengthof(p_hash) - 8, 8);
        } // End of function f_HashedId8FromSha384
        
garciay's avatar
garciay committed
         * @desc Compute the HashedId3 value from the HashedId8 value
         * @param p_hashp_hashedId8 The HashedId8 value
         * @return The HashedId3 value
         * @verdict Unchanged
         */
garciay's avatar
garciay committed
        function f_HashedId3FromHashedId8(
                                          in HashedId8 p_hashedId8
        ) return HashedId3 {
            return substr(p_hashedId8, lengthof(p_hashedId8) - 3, 3);
        }  // End of function f_HashedId3FromHashedId8
garciay's avatar
garciay committed
         * @desc    Verify the signature of the specified data
         * @param   p_toBeVerifiedData          The data to be verified
         * @param   p_certificateIssuer         The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
garciay's avatar
garciay committed
         * @param   p_signature                 The signature
         * @param   p_ecdsaNistp256PublicKeyCompressed   The compressed public key
         * @param   p_compressed_mode The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
garciay's avatar
garciay committed
         * @return  true on success, false otherwise
         */
        function f_verifyWithEcdsaNistp256WithSha256(
garciay's avatar
garciay committed
                                                     in octetstring p_toBeVerifiedData,
                                                     in Oct32 p_certificateIssuer,
                                                     in Oct64 p_signature,
                                                     in Oct32 p_ecdsaNistp256PublicKeyCompressed,
                                                     in integer p_compressed_mode
        ) return boolean {
//            log("f_verifyWithEcdsaNistp256WithSha256: toBeVerifiedData", p_toBeVerifiedData);
//            log("f_verifyWithEcdsaNistp256WithSha256: toBeVerifiedData length", lengthof(p_toBeVerifiedData));
//            log("f_verifyWithEcdsaNistp256WithSha256: signature", p_signature);
//            log("f_verifyWithEcdsaNistp256WithSha256: ecdsaNistp256PublicKeyCompressed", p_ecdsaNistp256PublicKeyCompressed);
            return fx_verifyWithEcdsaNistp256WithSha256(
                                                        p_toBeVerifiedData,
                                                        p_signature,
                                                        p_ecdsaNistp256PublicKeyCompressed,
                                                        p_compressed_mode
                                                        );
        } // End of function f_verifyWithEcdsaNistp256WithSha256
        
        /**
         * @desc    Verify the signature of the specified data
         * @param   p_toBeVerifiedData          The data to be verified
         * @param   p_certificateIssuer         The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
         * @param   p_signature                 The signature
         * @param   p_ecdsaNistp256PublicKeyX   The public key (x coordinate)
         * @param   p_ecdsaNistp256PublicKeyY   The public key (y coordinate)
         * @return  true on success, false otherwise
         */
        function f_verifyWithEcdsaNistp256WithSha256_1( // TODO To be removed
                                                       in octetstring p_toBeVerifiedData,
                                                       in Oct32 p_certificateIssuer,
                                                       in Oct64 p_signature,
                                                       in Oct32 p_ecdsaNistp256PublicKeyX,
                                                       in Oct32 p_ecdsaNistp256PublicKeyY
//            log("f_verifyWithEcdsaNistp256WithSha256: toBeVerifiedData", p_toBeVerifiedData);
//            log("f_verifyWithEcdsaNistp256WithSha256: toBeVerifiedData length", lengthof(p_toBeVerifiedData));
//            log("f_verifyWithEcdsaNistp256WithSha256: signature", p_signature);
//            log("f_verifyWithEcdsaNistp256WithSha256: ecdsaNistp256PublicKeyX", p_ecdsaNistp256PublicKeyX);
//            log("f_verifyWithEcdsaNistp256WithSha256: ecdsaNistp256PublicKeyY", p_ecdsaNistp256PublicKeyY);
            return fx_verifyWithEcdsaNistp256WithSha256_1(
                p_toBeVerifiedData,
                p_signature,
                p_ecdsaNistp256PublicKeyX,
                p_ecdsaNistp256PublicKeyY);
        } // End of function f_verifyWithEcdsaNistp256WithSha256_1
garciay's avatar
garciay committed
        /**
         * @Desc    Verify the signature of the specified data
         * @param   p_toBeVerifiedData          The data to be verified
         * @param   p_certificateIssuer         The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
garciay's avatar
garciay committed
         * @param   p_signature                 The signature
         * @param   p_ecdsaBrainpoolp256PublicKeyCompressed   The compressed public key
         * @param   p_compressed_mode The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
garciay's avatar
garciay committed
         * @return  true on success, false otherwise
         */
        function f_verifyWithEcdsaBrainpoolp256WithSha256(
                                                          in octetstring p_toBeVerifiedData,
                                                          in Oct32 p_certificateIssuer,
                                                          in Oct64 p_signature,
                                                          in Oct32 p_ecdsaBrainpoolp256PublicKeyCompressed,
                                                          in integer p_compressed_mode
        ) return boolean {
//            log("f_verifyWithEcdsaBrainpoolp256WithSha256: toBeVerifiedData", p_toBeVerifiedData);
//            log("f_verifyWithEcdsaBrainpoolp256WithSha256: toBeVerifiedData length", lengthof(p_toBeVerifiedData));
//            log("f_verifyWithEcdsaBrainpoolp256WithSha256: signature", p_signature);
//            log("f_verifyWithEcdsaBrainpoolp256WithSha256: ecdsaBrainpoolp256PublicKeyCompressed", p_ecdsaBrainpoolp256PublicKeyCompressed);
            return fx_verifyWithEcdsaBrainpoolp256WithSha256(
                                                             p_toBeVerifiedData,
                                                             p_signature,
                                                             p_ecdsaBrainpoolp256PublicKeyCompressed,
                                                             p_compressed_mode
                                                             );
        } // End of function f_verifyWithEcdsaBrainpoolp256WithSha256
        
        /**
         * @Desc    Verify the signature of the specified data
         * @param   p_toBeVerifiedData          The data to be verified
         * @param   p_certificateIssuer         The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
         * @param   p_signature                 The signature
         * @param   p_ecdsaBrainpoolp256PublicKeyX   The public key (x coordinate)
         * @param   p_ecdsaBrainpoolp256PublicKeyY   The public key (y coordinate)
         * @return  true on success, false otherwise
         */
        function f_verifyWithEcdsaBrainpoolp256WithSha256_1( // TODO To be removed
                                                            in octetstring p_toBeVerifiedData,
                                                            in Oct32 p_certificateIssuer,
                                                            in Oct64 p_signature,
                                                            in Oct32 p_ecdsaBrainpoolp256PublicKeyX,
                                                            in Oct32 p_ecdsaBrainpoolp256PublicKeyY
garciay's avatar
garciay committed
        ) return boolean {
//            log("f_verifyWithEcdsaBrainpoolp256WithSha256: toBeVerifiedData", p_toBeVerifiedData);
//            log("f_verifyWithEcdsaBrainpoolp256WithSha256: toBeVerifiedData length", lengthof(p_toBeVerifiedData));
//            log("f_verifyWithEcdsaBrainpoolp256WithSha256: signature", p_signature);
//            log("f_verifyWithEcdsaBrainpoolp256WithSha256: ecdsaBrainpoolp256PublicKeyX", p_ecdsaBrainpoolp256PublicKeyX);
//            log("f_verifyWithEcdsaBrainpoolp256WithSha256: ecdsaBrainpoolp256PublicKeyY", p_ecdsaBrainpoolp256PublicKeyY);
            return fx_verifyWithEcdsaBrainpoolp256WithSha256_1(
garciay's avatar
garciay committed
                p_toBeVerifiedData,
garciay's avatar
garciay committed
                p_signature,
                p_ecdsaBrainpoolp256PublicKeyX,
                p_ecdsaBrainpoolp256PublicKeyY);
        } // End of function f_verifyWithEcdsaBrainpoolp256WithSha256_1
garciay's avatar
garciay committed
        
        /**
         * @Desc    Verify the signature of the specified data
         * @param   p_toBeVerifiedData          The data to be verified
         * @param   p_certificateIssuer         The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
garciay's avatar
garciay committed
         * @param   p_signature                 The signature
         * @param   p_ecdsaBrainpoolp384PublicKeyX   The public key (x coordinate)
         * @param   p_ecdsaBrainpoolp384PublicKeyY   The public key (y coordinate)
         * @param   p_compressed_mode The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
garciay's avatar
garciay committed
         * @return  true on success, false otherwise
         */
        function f_verifyWithEcdsaBrainpoolp384WithSha384(
                                                          in octetstring p_toBeVerifiedData,
                                                          in Oct48 p_certificateIssuer,
                                                          in Oct96 p_signature,
                                                          in Oct48 p_ecdsaBrainpoolp384PublicKeyCompressed,
                                                          in integer p_compressed_mode
        ) return boolean {
//            log("f_verifyWithEcdsaBrainpoolp384WithSha384: toBeVerifiedData", p_toBeVerifiedData);
//            log("f_verifyWithEcdsaBrainpoolp384WithSha384: toBeVerifiedData length", lengthof(p_toBeVerifiedData));
//            log("f_verifyWithEcdsaBrainpoolp384WithSha384: signature", p_signature);
//            log("f_verifyWithEcdsaBrainpoolp384WithSha384: ecdsaBrainpoolp384PublicKeyCompressed", p_ecdsaBrainpoolp384PublicKeyCompressed);
            return fx_verifyWithEcdsaBrainpoolp384WithSha384(
                                                             p_toBeVerifiedData,
                                                             p_signature,
                                                             p_ecdsaBrainpoolp384PublicKeyCompressed,
                                                             p_compressed_mode
                                                             );
        } // End of function f_verifyWithEcdsaBrainpoolp384WithSha384
        
        /**
         * @Desc    Verify the signature of the specified data
         * @param   p_toBeVerifiedData          The data to be verified
         * @param   p_certificateIssuer         The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
         * @param   p_signature                 The signature
         * @param   p_ecdsaBrainpoolp384PublicKeyX   The public key (x coordinate)
         * @param   p_ecdsaBrainpoolp384PublicKeyY   The public key (y coordinate)
         * @return  true on success, false otherwise
         */
        function f_verifyWithEcdsaBrainpoolp384WithSha384_1( // TODO To be removed
                                                            in octetstring p_toBeVerifiedData,
                                                            in Oct48 p_certificateIssuer,
                                                            in Oct96 p_signature,
                                                            in Oct48 p_ecdsaBrainpoolp384PublicKeyX,
                                                            in Oct48 p_ecdsaBrainpoolp384PublicKeyY
garciay's avatar
garciay committed
        ) return boolean {
//            log("f_verifyWithEcdsaBrainpoolp384WithSha384: toBeVerifiedData", p_toBeVerifiedData);
//            log("f_verifyWithEcdsaBrainpoolp384WithSha384: toBeVerifiedData length", lengthof(p_toBeVerifiedData));
//            log("f_verifyWithEcdsaBrainpoolp384WithSha384: signature", p_signature);
//            log("f_verifyWithEcdsaBrainpoolp384WithSha384: ecdsaBrainpoolp384PublicKeyX", p_ecdsaBrainpoolp384PublicKeyX);
//            log("f_verifyWithEcdsaBrainpoolp384WithSha384: ecdsaBrainpoolp384PublicKeyY", p_ecdsaBrainpoolp384PublicKeyY);
            return fx_verifyWithEcdsaBrainpoolp384WithSha384_1(
garciay's avatar
garciay committed
                p_toBeVerifiedData,
garciay's avatar
garciay committed
                p_signature,
                p_ecdsaBrainpoolp384PublicKeyX,
                p_ecdsaBrainpoolp384PublicKeyY);
        } // End of function f_verifyWithEcdsaBrainpoolp384WithSha384_1
        /**
         * @desc    Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm.
         *          This function should not be used by the ATS
         * @param   p_privateKey    The new private key value
         * @param   p_publicKeyX    The new public key value (x coordinate)
         * @param   p_publicKeyX    The new public key value (y coordinate)
         * @param   p_publicKeyCompressed The compressed public keys
         * @param   p_compressed_mode The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
         * @return  true on success, false otherwise
         */
garciay's avatar
garciay committed
        function f_generate_key_pair_nistp256(
garciay's avatar
garciay committed
                                              out Oct32 p_privateKey,
                                              out Oct32 p_publicKeyX,
                                              out Oct32 p_publicKeyY,
                                              out Oct32 p_publicKeyCompressed,
                                              out integer p_compressed_mode
garciay's avatar
garciay committed
                                             ) return boolean {
          log(">>> f_generate_key_pair_nistp256");
          
          if (PICS_SEC_FIXED_KEYS) { // Debug mode: Use fixed values
           p_privateKey := '43481BC44C073C1432DB6EC4F0EF57062BEA08E4C19F811567325AD1FD1C6577'O;
           p_publicKeyX := '0B5D74B033531C51D17B4F218DD4E39289AE4BF2EE3D7BAB7C07DAF0C14F0317'O;
           p_publicKeyY := '5D49B139A9237832FDE24D77555878CE65D6C2284A1BDA4CE08ABDD4071E0255'O;
           p_publicKeyCompressed := '0B5D74B033531C51D17B4F218DD4E39289AE4BF2EE3D7BAB7C07DAF0C14F0317'O;
           p_compressed_mode := 1;
garciay's avatar
garciay committed

           return true;
         }
          return fx_generateKeyPair_nistp256(p_privateKey, p_publicKeyX, p_publicKeyY, p_publicKeyCompressed, p_compressed_mode);
garciay's avatar
garciay committed
        }
        
        /**
         * @desc    Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm.
         *          This function should not be used by the ATS
         * @param   p_privateKey    The new private key value
         * @param   p_publicKeyX    The new public key value (x coordinate)
         * @param   p_publicKeyX    The new public key value (y coordinate)
         * @param   p_publicKeyCompressed The compressed public keys
         * @param   p_compressed_mode The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
garciay's avatar
garciay committed
         * @return  true on success, false otherwise
         */
        function f_generate_key_pair_brainpoolp256(
garciay's avatar
garciay committed
                                                   out Oct32 p_privateKey,
                                                   out Oct32 p_publicKeyX,
                                                   out Oct32 p_publicKeyY,
                                                   out Oct32 p_publicKeyCompressed,
                                                   out integer p_compressed_mode
garciay's avatar
garciay committed
                                                  ) return boolean {
          log(">>> f_generate_key_pair_brainpoolp256");
          return fx_generateKeyPair_brainpoolp256(p_privateKey, p_publicKeyX, p_publicKeyY, p_publicKeyCompressed, p_compressed_mode);
garciay's avatar
garciay committed
        }
        
        /**
         * @desc    Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm.
         *          This function should not be used by the ATS
         * @param   p_privateKey    The new private key value
         * @param   p_publicKeyX    The new public key value (x coordinate)
         * @param   p_publicKeyX    The new public key value (y coordinate)
         * @param   p_publicKeyCompressed The compressed public keys
         * @param   p_compressed_mode The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
garciay's avatar
garciay committed
         * @return  true on success, false otherwise
         */
        function f_generate_key_pair_brainpoolp384(
garciay's avatar
garciay committed
                                                   out Oct48 p_privateKey,
                                                   out Oct48 p_publicKeyX,
                                                   out Oct48 p_publicKeyY,
                                                   out Oct48 p_publicKeyCompressed,
                                                   out integer p_compressed_mode
garciay's avatar
garciay committed
                                                  ) return boolean {
          return fx_generateKeyPair_brainpoolp384(p_privateKey, p_publicKeyX, p_publicKeyY, p_publicKeyCompressed, p_compressed_mode);
garciay's avatar
garciay committed
        /**
        * @desc    Calculate digest over the certificate
        * @param   p_cert The certificate
        * @return  the HashedId8 value
        * @see Draft ETSI TS 103 097 V1.1.14 Clause 4.2.13   HashedId8
        */
        function f_calculateDigestFromCertificate(
                                                  in Certificate p_cert
        ) return HashedId8 {
            var octetstring v_hash;
            
            if (PICS_SEC_SHA256) {
garciay's avatar
garciay committed
                v_hash := f_calculateDigestSha256FromCertificate(p_cert);
            } if (PICS_SEC_SHA384) {
garciay's avatar
garciay committed
                v_hash := f_calculateDigestSha384FromCertificate(p_cert);
            } 
            
            return substr(v_hash, lengthof(v_hash) - 8, 8);
        } // End of function f_calculateDigestFromCertificate
        
        * @desc    Calculate digest over the certificate
        * @param   p_cert The certificate
        * @return  the HashedId8 value
        * @see Draft ETSI TS 103 097 V1.1.14 Clause 4.2.13   HashedId8
garciay's avatar
garciay committed
        function f_calculateDigestSha256FromCertificate(
                                                        in EtsiTs103097Certificate p_cert
            var octetstring v_toBeHashedData;
            var octetstring v_hash;
            v_toBeHashedData := bit2oct(encvalue(p_cert));
            v_hash := f_hashWithSha256(v_toBeHashedData);
            return substr(v_hash, lengthof(v_hash) - 8, 8);
garciay's avatar
garciay committed
        } // End of function f_calculateDigestSha256FromCertificate
        
        function f_calculateDigestSha384FromCertificate(
                                                        in EtsiTs103097Certificate p_cert
        ) return HashedId8 {
            var octetstring v_toBeHashedData;
            var octetstring v_hash;
                        
            v_toBeHashedData := bit2oct(encvalue(p_cert));
            v_hash := f_hashWithSha384(v_toBeHashedData);
            return substr(v_hash, lengthof(v_hash) - 8, 8);
        } // End of function f_calculateDigestSha384FromCertificate
garciay's avatar
garciay committed
        function f_duration2time(
                                 in Duration p_duration
        ) return UInt16 {
            if (ischosen(p_duration.seconds)) {
                return p_duration.seconds;
            } else if (ischosen(p_duration.minutes)) { 
                return p_duration.minutes;
            } else if (ischosen(p_duration.hours)) { 
                return p_duration.hours;
            } else if (ischosen(p_duration.sixtyHours)) {
                return p_duration.sixtyHours;
            } else if (ischosen(p_duration.years)) {
                return p_duration.years;
garciay's avatar
garciay committed
            }
            
            return 0; // Unrechable code
garciay's avatar
garciay committed
        } // End of function f_duration2time
        
        group hostSignatureHelpers {
            /**
            * @desc    Initialize [out] certificates according to the specified certificate name
            * @param   p_certificateName The certificate name to be used
            * @param   p_aaCertificate The AA certificate [out]
            * @param   p_atCertificate The AT certificate [out]
            * @return  true on succes, false otherwise
            * @see Draft ETSI TS 103 097 V1.1.14 Clause 4.2.13   HashedId8
            function f_prepareCertificates(
                                           in template (omit) charstring p_certificateName,
                                           out EtsiTs103097Certificate p_aaCertificate,
                                           out EtsiTs103097Certificate p_atCertificate
            ) runs on ItsSecurityBaseComponent return boolean {
garciay's avatar
garciay committed
                //log(">>> f_prepareCertificates: ", p_certificateName);
                
                // Load certificates if required
garciay's avatar
garciay committed
                if ((lengthof(p_certificateName) > 0) and (valueof(p_certificateName) != cc_taCert_A)) {
                    var HashedId8 v_digest;
                    var charstring v_cert;
                    
                    if (f_readCertificate(valueof(p_certificateName), p_atCertificate) == false){
garciay's avatar
garciay committed
                        log("f_prepareCertificates: Failed to read certificate ", p_certificateName);
                        return false;
                    }
                    if (ischosen(p_atCertificate.issuer.sha256AndDigest)) {
                        v_digest := p_atCertificate.issuer.sha256AndDigest;
                    } else if (ischosen(p_atCertificate.issuer.sha384AndDigest)) {
                        v_digest := p_atCertificate.issuer.sha384AndDigest;
                    } else {
                        log("f_prepareCertificates: Invalid certificate issuer ", p_atCertificate.issuer);
                        return false;
                    }
garciay's avatar
garciay committed
                    if (f_getCertificateFromDigest(v_digest, p_aaCertificate) == false) {
                        log("f_prepareCertificates: Failed to read certificate issuer ", v_digest);
                        return false;
                    }
                } else {
                    p_atCertificate := vc_atCertificate;
                    p_aaCertificate := vc_aaCertificate;
Yann Garcia's avatar
Yann Garcia committed
                // Store the certificate to build this message
                vc_lastAtCertificateUsed := p_atCertificate;
                
                return true;
            } // End of function f_prepareCertificates
berge's avatar
berge committed
             * @desc  This function build and sign the SecureMessage part covered by the signature process
             * @param p_securedMessage      The signed  SecureMessage part
             * @param p_payloadField       Payloads to be included in the message
berge's avatar
berge committed
             * @param p_mandatoryHeaders    Mandatory headers for the selected profile 
             * @param p_headerInfo        HeaderInfo to be inserted in the message
berge's avatar
berge committed
             * @param p_securityProfile     Selected security profile
             * @return true on success, false otherwise
             */
            function f_buildGnSecuredMessage(
garciay's avatar
garciay committed
                                             inout EtsiTs103097Data p_securedMessage,
garciay's avatar
garciay committed
                                             in charstring p_certificateName,
                                             in ToBeSignedData p_payloadField
            ) runs on ItsSecurityBaseComponent return boolean {
                // Local variables
                var octetstring v_secPayload, v_signature;
garciay's avatar
garciay committed
                var ToBeSignedData v_toBeSignedData;
                var octetstring v_certificateIssuer;
                var octetstring v_privateKey;
Yann Garcia's avatar
Yann Garcia committed
                log(">>> f_buildGnSecuredMessage: p_securedMessage=", p_securedMessage);
                log(">>> f_buildGnSecuredMessage: p_payloadField=", p_payloadField);
                // Prepare payload to be signed
garciay's avatar
garciay committed
                v_toBeSignedData := valueof(p_payloadField);
                v_secPayload := bit2oct(encvalue(v_toBeSignedData));
                
                // Signed payload
                if (ispresent(p_certificateName) and (valueof(p_certificateName) != cc_taCert_A)) {
                    if(not f_readSigningKey(valueof(p_certificateName), v_privateKey)){
                        return false;
                    }
                } else {
filatov's avatar
filatov committed
                    if(not f_readSigningKey(cc_taCert_A, v_privateKey)){
                f_getCertificateHash(p_certificateName, v_certificateIssuer);
garciay's avatar
garciay committed
                if (ischosen(p_securedMessage.content.signedData.signature_.ecdsaNistP256Signature)) {
Yann Garcia's avatar
Yann Garcia committed
                  v_signature := f_signWithEcdsaNistp256WithSha256(
                                                                   v_secPayload,
                                                                   v_certificateIssuer,
                                                                   v_privateKey 
                                                                   );
                  p_securedMessage.content.signedData.signature_ := valueof(m_signature_ecdsaNistP256(
                                                                                                      m_ecdsaP256Signature(
                                                                                                                           m_eccP256CurvePoint_x_only(substr(v_signature, 0, 32)),
                                                                                                                           substr(v_signature, 32, 32)
                                                                                                                           )
                                                                                                      ));
garciay's avatar
garciay committed
                } else if (ischosen(p_securedMessage.content.signedData.signature_.ecdsaBrainpoolP256r1Signature)) {
                    v_signature := f_signWithEcdsaBrainpoolp256WithSha256(
Yann Garcia's avatar
Yann Garcia committed
                                                                          v_secPayload,
                                                                          v_certificateIssuer, 
                                                                          v_privateKey 
                                                                          );
garciay's avatar
garciay committed
                    p_securedMessage.content.signedData.signature_ := valueof(m_signature_ecdsaBrainpoolP256r1(
Yann Garcia's avatar
Yann Garcia committed
                                                                                                               m_ecdsaP256Signature(
                                                                                                                                    m_eccP256CurvePoint_x_only(substr(v_signature, 0, 32)),
                                                                                                                                    substr(v_signature, 32, 32)
                                                                                                                                    )
                                                                                                               ));
                } else if (ischosen(p_securedMessage.content.signedData.signature_.ecdsaBrainpoolP384r1Signature)) {
Yann Garcia's avatar
Yann Garcia committed
                  v_signature := f_signWithEcdsaBrainpoolp384WithSha384(
                                                                        v_secPayload,
                                                                        v_certificateIssuer, 
                                                                        v_privateKey 
                                                                        );
                  p_securedMessage.content.signedData.signature_ := valueof(m_signature_ecdsaBrainpoolP384r1(
                                                                                                             m_ecdsaP384Signature(
                                                                                                                                  m_eccP384CurvePoint_x_only(substr(v_signature, 0, 32)),
                                                                                                                                  substr(v_signature, 32, 32)
                                                                                                                                  )
                                                                                                             ));
garciay's avatar
garciay committed
                } // TODO To be continued
Yann Garcia's avatar
Yann Garcia committed
                log("<<< f_buildGnSecuredMessage: p_securedMessage=", p_securedMessage);
garciay's avatar
garciay committed
                return true;
            } // End of function f_buildGnSecuredMessage
            
            /**
             * @desc  This function build and sign the SecureMessage part covered by the signature process including wrong elements of protocols. It is used for BO test cases
             * @param p_securedMessage      The signed  SecureMessage part
             * @param p_certificateName     The certificate name
             * @param  p_protocolVersion    The protocol version to be set. Default: 2
             * @param  p_trailerStatus      The Traile behaviour:
             *                              <li>0 for no trailer</li>
             *                              <li>1 for invalid trailer</li>
             *                              <li>2 for duplicated trailer</li>
             * @param p_payloadField        Payloads to be included in the message
             * @param p_mandatoryHeaders    Mandatory headers for the selected profile 
             * @param p_headerInfo        HeaderInfo to be inserted in the message
             * @param p_securityProfile     Selected security profile
             * @return true on success, false otherwise
             */
            function f_buildGnSecuredMessage_Bo(
garciay's avatar
garciay committed
                                                inout EtsiTs103097Data p_securedMessage,
                                                in template (value) charstring p_certificateName,
garciay's avatar
garciay committed
                                                in UInt8 p_protocolVersion := c_protocol_version,
                                                in integer p_trailerStatus := 0,
garciay's avatar
garciay committed
                                                in template (value) ToBeSignedData p_payloadField,
                                                in template (value) HeaderInfo p_mandatoryHeaders,
                                                in template (omit) HeaderInfo p_headerInfo := omit
            ) return boolean {
                
                // Local variables
                var octetstring v_secPayload, v_signature;
                var template (value) ToBeSignedData v_toBeSignedData;
                var integer i, j, k, n;
                var HeaderInfo v_headerFields := {};
                var Ieee1609Dot2Content v_toBeSignedPayload;
                var Oct32 v_privateKey;
                var UInt8 v_trailerSize;
                
                // Prepare headers
                if (not(ispresent(p_headerInfo))) {
                    v_headerFields := valueof(p_mandatoryHeaders);
                } else {/* FIXME To be reviewed 
                    // Merge p_headerInfo and v_mandatoryHeaders into v_headerFields
                    i := 0; // index for p_headerInfo
                    j := 0; // index for v_mandatoryHeaders
                    k := 0; // index for v_headerFields
                        
                    // Special processing for signer_info
                    if (lengthof(valueof(p_headerInfo)) > 0 and valueof(p_headerInfo[i].type_) == e_signer_info) {
                        v_headerFields[k] := valueof(p_headerInfo[i]);
                        k := k + 1;
                        i := i + 1;
                    }
                    
                    for (j := j; j < lengthof(p_mandatoryHeaders); j := j + 1) {
                        // Search for mandatory header in p_HeaderFields
                        for (n := 0; n < lengthof(p_headerInfo); n := n + 1) {
                            if (valueof(p_headerInfo[n].type_) == valueof(p_mandatoryHeaders[j].type_)) {
                                // mandatory header already in p_HeaderFields
                                break;
                            }
                        } // End of 'for' statement
                        if (n >= lengthof(p_headerInfo)) {
                            if (valueof(p_mandatoryHeaders[j].type_) != e_signer_info) {
                                // Add headers from p_headerInfo having lower number than mandatory header
                                for (n := i; n < lengthof(p_headerInfo) and valueof(p_headerInfo[n].type_) < valueof(p_mandatoryHeaders[j].type_); n := n + 1) {
                                    v_headerFields[k] := valueof(p_headerInfo[n]);
                                    k := k + 1;
                                    i := i + 1;
                                }
                            }
                            // Add mandatory header
                            v_headerFields[k] := valueof(p_mandatoryHeaders[j]);
                            k := k + 1;
                        }
                    } // End of 'for' statement
                        
                    // Add remaining headers from p_HeaderFields
                    for ( i := i; i < lengthof(p_headerInfo); i := i + 1) {
                        // Add headers from p_headerInfo having lower number than mandatory header
                        v_headerFields[k] := valueof(p_headerInfo[i]);
                        k := k + 1;
                    } // End of 'for' statement
                
                // Prepare payload to be signed
                /* FIXME To be reviewed v_toBeSignedPayload := valueof(p_payloadField);
garciay's avatar
garciay committed
//                log("p_trailerStatus=", p_trailerStatus);
                if (p_trailerStatus == 0) {
                    v_trailerSize := 0;
                } else if (p_trailerStatus == 1) {
                    v_trailerSize := 67;
                } else if (p_trailerStatus == 2) {
                    v_trailerSize := 2 * 67;
                } else {
                    v_trailerSize := 67;
                }
                v_toBeSignedData := m_toBeSignedSecuredMessage_wrong_protocol(
                    v_headerFields,
                    v_toBeSignedPayload,
                    e_signature,
                    p_protocolVersion,
                    v_trailerSize
                );*/
//                log("m_toBeSignedSecuredMessage_wrong_protocol=", v_toBeSignedData);
                /* FIXME To be reviewedv_secPayload := bit2oct(encvalue(v_toBeSignedData));
garciay's avatar
garciay committed
//                log("v_secPayload=", v_secPayload);
                
                // Signed payload
                if (ispresent(p_certificateName) and (valueof(p_certificateName) != cc_taCert_A)) {
                    if(not f_readSigningKey(valueof(p_certificateName), v_privateKey)){
                        return false;
                    }
                } else {
filatov's avatar
filatov committed
                    if(not f_readSigningKey(cc_taCert_A, v_privateKey)){
                        return false;
                    }
                }
                v_signature := f_signWithEcdsaNistp256WithSha256(
                    v_secPayload, 
                    v_privateKey 
garciay's avatar
garciay committed
//                log("v_signature=", v_signature);
garciay's avatar
garciay committed
//                log("p_trailerStatus=", p_trailerStatus);