Function implementing YubiHSM AEAD encrypt/decrypt in software.
558466
def aesCCM(key, key_handle, nonce, data, decrypt=False):
    
    if decrypt:
        (data, saved_mac) = _split_data(data, len(data) - pyhsm.defines.YSM_AEAD_MAC_SIZE)

    nonce = pyhsm.util.input_validate_nonce(nonce, pad = True)
    mac = _cbc_mac(key, key_handle, nonce, len(data))

    counter = _ctr_counter(key_handle, nonce, value = 0)
    ctr_aes = AES.new(key, AES.MODE_CTR, counter = counter.next)
    out = []
    while data:
        (thisblock, data) = _split_data(data, pyhsm.defines.YSM_BLOCK_SIZE)

        # encrypt/decrypt and CBC MAC
        if decrypt:
            aes_out = ctr_aes.decrypt(thisblock)
            mac.update(aes_out)
        else:
            mac.update(thisblock)
            aes_out = ctr_aes.encrypt(thisblock)

        out.append(aes_out)

    # Finalize MAC
    counter.value = 0
    mac.finalize(counter.pack())
    if decrypt:
        if mac.get() != saved_mac:
            raise pyhsm.exception.YHSM_Error('AEAD integrity check failed')
    else:
        out.append(mac.get())
    return ''.join(out)
590721
function encodePBES2(decoded){
  const epki = { encryptionAlgorithm: {} };

  // algorithm
  epki.encryptionAlgorithm.algorithm = params.passwordBasedEncryptionSchemes[decoded.encryptionAlgorithm.algorithm].oid;

  // kdf
  const kdf = decoded.encryptionAlgorithm.parameters.keyDerivationFunc;
  if(kdf.algorithm === 'pbkdf2') {
    kdf.parameters.prf.algorithm = params.pbkdf2Prfs[kdf.parameters.prf.algorithm].oid;
    kdf.parameters = PBKDF2Params.encode(kdf.parameters, 'der');
  } else throw new Error('UnsupportedKDF');
  kdf.algorithm = params.keyDerivationFunctions[kdf.algorithm].oid;

  // encryptionScheme
  const eS = decoded.encryptionAlgorithm.parameters.encryptionScheme;
  if(Object.keys(PBES2ESParams).indexOf(eS.algorithm) >= 0){
    eS.parameters = PBES2ESParams[eS.algorithm].encode(eS.parameters, 'der');
  } else throw new Error('UnsupportedCipher');
  eS.algorithm = params.encryptionSchemes[eS.algorithm].oid;

  // params
  epki.encryptionAlgorithm.parameters = PBES2Params.encode({ keyDerivationFunc: kdf, encryptionScheme: eS }, 'der');

  // encoded data
  epki.encryptedData = decoded.encryptedData;
  return EncryptedPrivateKeyInfo.encode(epki, 'der');
}
953412
def encode(password, algorithm, salt, iterations):
    
    hash = hashlib.pbkdf2_hmac(digest().name, password.encode(), salt.encode(), iterations)
    encoded = base64.b64encode(hash).decode('ascii').strip()
    return "%s$%d$%s$%s" % (algorithm, iterations, salt, encoded)
609900
def encrypt(message, modN, e, blockSize):
    """"""
    numList = string2numList(message)
    numBlocks = numList2blocks(numList, blockSize)  # only one block
    message = numBlocks[0]
    # return [modExp(blocks, e, modN) for blocks in numBlocks]
    return modExp(message, e, modN)
1070715
def _decrypt(file_contents, password):
  

  # Extract the salt, iterations, hmac, initialization vector, and ciphertext
  # from 'file_contents'.  These five values are delimited by
  # '_ENCRYPTION_DELIMITER'.  This delimiter is arbitrarily chosen and should
  # not occur in the hexadecimal representations of the fields it is
  # separating.  Raise 'securesystemslib.exceptions.CryptoError', if
  # 'file_contents' does not contains the expected data layout.
  try:
    salt, iterations, hmac, iv, ciphertext = \
      file_contents.split(_ENCRYPTION_DELIMITER)

  except ValueError:
    raise securesystemslib.exceptions.CryptoError('Invalid encrypted file.')

  # Ensure we have the expected raw data for the delimited cryptographic data.
  salt = binascii.unhexlify(salt.encode('utf-8'))
  iterations = int(iterations)
  iv = binascii.unhexlify(iv.encode('utf-8'))
  ciphertext = binascii.unhexlify(ciphertext.encode('utf-8'))

  # Generate derived key from 'password'.  The salt and iterations are
  # specified so that the expected derived key is regenerated correctly.
  # Discard the old "salt" and "iterations" values, as we only need the old
  # derived key.
  junk_old_salt, junk_old_iterations, symmetric_key = \
    _generate_derived_key(password, salt, iterations)

  # Verify the hmac to ensure the ciphertext is valid and has not been altered.
  # See the encryption routine for why we use the encrypt-then-MAC approach.
  # The decryption routine may verify a ciphertext without having to perform
  # a decryption operation.
  generated_hmac_object = \
    cryptography.hazmat.primitives.hmac.HMAC(symmetric_key, hashes.SHA256(),
        backend=default_backend())
  generated_hmac_object.update(ciphertext)
  generated_hmac = binascii.hexlify(generated_hmac_object.finalize())


  if not securesystemslib.util.digests_are_equal(generated_hmac.decode(), hmac):
    raise securesystemslib.exceptions.CryptoError('Decryption failed.')

  # Construct a Cipher object, with the key and iv.
  decryptor = Cipher(algorithms.AES(symmetric_key), modes.CTR(iv),
      backend=default_backend()).decryptor()

  # Decryption gets us the authenticated plaintext.
  plaintext = decryptor.update(ciphertext) + decryptor.finalize()

  return plaintext
847476
def _decrypt(self, data, key):
        """"""
        seed1 = key
        seed2 = 0xEEEEEEEE
        result = BytesIO()

        for i in range(len(data) // 4):
            seed2 += self.encryption_table[0x400 + (seed1 & 0xFF)]
            seed2 &= 0xFFFFFFFF
            value = struct.unpack("<I", data[i*4:i*4+4])[0]
            value = (value ^ (seed1 + seed2)) & 0xFFFFFFFF

            seed1 = ((~seed1 << 0x15) + 0x11111111) | (seed1 >> 0x0B)
            seed1 &= 0xFFFFFFFF
            seed2 = value + seed2 + (seed2 << 5) + 3 & 0xFFFFFFFF

            result.write(struct.pack("<I", value))

        return result.getvalue()
1150988
def _encrypt(self, dec, password=None):
        
        if AES is None:
            raise ImportError("PyCrypto required")

        if password is None:
            password = self.password

        if password is None:
            raise ValueError(
                "Password need to be provided to create encrypted archives")

        # generate the different encryption parts (non-secure!)
        master_key = Random.get_random_bytes(32)
        master_salt = Random.get_random_bytes(64)
        user_salt = Random.get_random_bytes(64)
        master_iv = Random.get_random_bytes(16)
        user_iv = Random.get_random_bytes(16)
        rounds = 10000

        # create the PKCS#7 padding
        l = len(dec)
        pad = 16 - (l % 16)
        dec += bytes([pad] * pad)

        # encrypt the data
        cipher = AES.new(master_key, IV=master_iv, mode=AES.MODE_CBC)
        enc = cipher.encrypt(dec)

        # generate the master key checksum
        master_ck = PBKDF2(self.encode_utf8(master_key),
                           master_salt, dkLen=256//8, count=rounds)

        # generate the user key from the given password
        user_key = PBKDF2(password,
                          user_salt, dkLen=256//8, count=rounds)

        # encrypt the master key and iv
        master_dec = b"\x10" + master_iv + b"\x20" + master_key + b"\x20" + master_ck
        l = len(master_dec)
        pad = 16 - (l % 16)
        master_dec += bytes([pad] * pad)
        cipher = AES.new(user_key, IV=user_iv, mode=AES.MODE_CBC)
        master_enc = cipher.encrypt(master_dec)

        # put everything together
        enc = binascii.b2a_hex(user_salt).upper() + b"\n" + \
                binascii.b2a_hex(master_salt).upper() + b"\n" + \
                str(rounds).encode() + b"\n" + \
                binascii.b2a_hex(user_iv).upper() + b"\n" + \
                binascii.b2a_hex(master_enc).upper() + b"\n" + enc

        return enc
487339
def parse_args():
    
    global default_device

    parser = argparse.ArgumentParser(description = "Generate password AEAD using YubiHSM",
                                     add_help=True
                                     )
    parser.add_argument('-D', '--device',
                        dest='device',
                        default=default_device,
                        required=False,
                        help='YubiHSM device (default : "%s").' % default_device
                        )
    parser.add_argument('-v', '--verbose',
                        dest='verbose',
                        action='store_true', default=False,
                        help='Enable verbose operation.'
                        )
    parser.add_argument('--debug',
                        dest='debug',
                        action='store_true', default=False,
                        help='Enable debug operation.'
                        )
    parser.add_argument('--key-handle',
                        type=int, dest='key_handle',
                        required=True,
                        help='Key handle to use. Must have YHSM_ECB_BLOCK_ENCRYPT and/or YHSM_ECB_BLOCK_DECRYPT_CMP flag set.'
                        )
    parser.add_argument('-N', '--nonce',
                        dest='nonce',
                        required=True,
                        help='Nonce to use. 6 bytes encoded as 12 chars hex.'
                        )
    parser.add_argument('--set',
                        dest='set',
                        action='store_true', default=False,
                        help='Set password mode.'
                        )
    parser.add_argument('--validate',
                        dest='validate',
                        help='AEAD to validate.'
                        )
    parser.add_argument('--min_length',
                        type=int, dest='min_len',
                        required=False, default=20,
                        help='Minimum length to pad passwords to (default: 20).'
                        )

    args = parser.parse_args()

    if args.set and args.validate:
        sys.stderr.write("Arguments --set and --validate are mutually exclusive.\n")
        sys.exit(1)
    if not args.set and not args.validate:
        sys.stderr.write("Either --set or --validate must be specified.\n")
        sys.exit(1)

    return args
910617
def parse_args():
    
    parser = argparse.ArgumentParser(
        description="Import existing secrets to YubiHSM eco system",
        add_help=True, formatter_class=argparse.ArgumentDefaultsHelpFormatter,)
    parser.add_argument('-D', '--device',
                        dest='device',
                        default=default_device,
                        required=False,
                        help='YubiHSM device',
                        )
    parser.add_argument('-O', '--output-dir', '--aead-dir',
                        dest='output_dir',
                        default=default_dir,
                        required=False,
                        help='Output directory (AEAD base dir)',
                        metavar='DIR',
                        )
    parser.add_argument('-v', '--verbose',
                        dest='verbose',
                        action='store_true', default=False,
                        help='Enable verbose operation',
                        )
    parser.add_argument('--debug',
                        dest='debug',
                        action='store_true', default=False,
                        help='Enable debug operation',
                        )
    parser.add_argument('--public-id-chars',
                        dest='public_id_chars',
                        type=int, default=default_public_id_chars,
                        required=False,
                        help='Number of chars in generated public ids',
                        metavar='NUM',
                        )
    parser.add_argument(
        '--key-handles',
        dest='key_handles',
        nargs='+',
        required=True,
        help='Key handle(s) to encrypt the imported secrets with',
        metavar='HANDLE',
     )
    parser.add_argument('--internal-db',
                        dest='internal_db',
                        action='store_true', default=False,
                        help='Store key in YubiHSM internal database',
                        )
    parser.add_argument(
        '--aes-key',
        dest='aes_key',
        required=False,
        default=None,
        help='AES key to use when generating AEADs (no YubiHSM)',
        metavar='HEXSTR',
     )
    parser.add_argument('--random-nonce',
                        dest='random_nonce',
                        action='store_true', default=False,
                        help='Let the HSM generate random nonce',
                        )

    args = parser.parse_args()
    if args.internal_db:
        if len(args.key_handles) != 1:
            sys.stderr.write("--internal-db requires exactly one key handle.\n")
            sys.exit(1)
        if args.aes_key:
            sys.stderr.write("--internal-db incompatible with --aes-key.\n")
            sys.exit(1)
    return args
373289
def encrypt_binary(self, binary, *args, **kwargs):
        
        return self.encrypt(binary, *args, **kwargs)
53600
def encrypt(self, msg):
        """"""
        iv = self.random_bytes(AES.block_size)
        ctr = Counter.new(AES.block_size * 8, initial_value=self.bin2long(iv))
        cipher = AES.AESCipher(self._cipherkey, AES.MODE_CTR, counter=ctr)
        cipher_text = cipher.encrypt(msg)
        intermediate = iv + cipher_text
        signature = self.sign(intermediate)
        return signature + intermediate
710131
def customPRF512(key, amac, smac, anonce, snonce):
    """"""
    A = b"Pairwise key expansion"
    B = b"".join(sorted([amac, smac]) + sorted([anonce, snonce]))

    blen = 64
    i = 0
    R = b''
    while i <= ((blen * 8 + 159) / 160):
        hmacsha1 = hmac.new(key, A + chb(0x00) + B + chb(i), hashlib.sha1)
        i += 1
        R = R + hmacsha1.digest()
    return R[:blen]
738797
def encrypt(source, dest, keys):
    """"""
    cmd = flatten([gnupg_bin(), "--armor", "--output", dest, gnupg_verbose(),
                   gnupg_home(), recipients_args(keys),
                   "--encrypt", source])

    stderr_output(cmd)
    return True
437019
function _encryptBlock($in)
    {
        $state = array();
        $words = unpack('N*word', $in);

        $w = $this->w;
        $t0 = $this->t0;
        $t1 = $this->t1;
        $t2 = $this->t2;
        $t3 = $this->t3;
        $Nb = $this->Nb;
        $Nr = $this->Nr;
        $c = $this->c;

        // addRoundKey
        $i = 0;
        foreach ($words as $word) {
            $state[] = $word ^ $w[0][$i++];
        }

        // fips-197.pdf#page=19, "Figure 5. Pseudo Code for the Cipher", states that this loop has four components - 
        // subBytes, shiftRows, mixColumns, and addRoundKey. fips-197.pdf#page=30, "Implementation Suggestions Regarding 
        // Various Platforms" suggests that performs enhanced implementations are described in Rijndael-ammended.pdf.
        // Rijndael-ammended.pdf#page=20, "Implementation aspects / 32-bit processor", discusses such an optimization.
        // Unfortunately, the description given there is not quite correct.  Per aes.spec.v316.pdf#page=19 [1], 
        // equation (7.4.7) is supposed to use addition instead of subtraction, so we'll do that here, as well.

        // [1] http://fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.v316.pdf
        $temp = array();
        for ($round = 1; $round < $Nr; $round++) {
            $i = 0; // $c[0] == 0
            $j = $c[1];
            $k = $c[2];
            $l = $c[3];

            while ($i < $this->Nb) {
                $temp[$i] = $t0[$state[$i] & 0xFF000000] ^ 
                            $t1[$state[$j] & 0x00FF0000] ^ 
                            $t2[$state[$k] & 0x0000FF00] ^ 
                            $t3[$state[$l] & 0x000000FF] ^ 
                            $w[$round][$i];
                $i++;
                $j = ($j + 1) % $Nb;
                $k = ($k + 1) % $Nb;
                $l = ($l + 1) % $Nb;
            }

            for ($i = 0; $i < $Nb; $i++) {
                $state[$i] = $temp[$i];
            }
        }

        // subWord
        for ($i = 0; $i < $Nb; $i++) {
            $state[$i] = $this->_subWord($state[$i]);
        }

        // shiftRows + addRoundKey
        $i = 0; // $c[0] == 0
        $j = $c[1];
        $k = $c[2];
        $l = $c[3];
        while ($i < $this->Nb) {
            $temp[$i] = ($state[$i] & 0xFF000000) ^ 
                        ($state[$j] & 0x00FF0000) ^ 
                        ($state[$k] & 0x0000FF00) ^ 
                        ($state[$l] & 0x000000FF) ^
                         $w[$Nr][$i];
            $i++;
            $j = ($j + 1) % $Nb;
            $k = ($k + 1) % $Nb;
            $l = ($l + 1) % $Nb;
        }
        $state = $temp;

        array_unshift($state, 'N*');

        return call_user_func_array('pack', $state);
    }
352681
def decrypt(message, hash: nil)
      # 0
      message = Base64.decode64(message)
      hmac = message[0..63] # 64 bits of hmac signature

      case
      when hash && hmac != hash
        raise Error, "Provided hash mismatch for encrypted file!"
      when hmac != hmac_signature(message[64..-1])
        raise Error, "HMAC signature mismatch for encrypted file!"
      end

      # 1
      rsa_encrypted_aes_key = message[64..319]  # next 256 bits
      rsa_encrypted_aes_iv  = message[320..575] # next 256 bits
      aes_encrypted_message = message[576..-1]

      # 2
      aes_key = @rsa.private_decrypt rsa_encrypted_aes_key
      aes_iv  = @rsa.private_decrypt rsa_encrypted_aes_iv

      # 3
      @cipher.reset
      @cipher.decrypt
      @cipher.key = aes_key
      @cipher.iv  = aes_iv
      content = @cipher.update(aes_encrypted_message) + @cipher.final

      { signature: hmac, content: content }
    rescue OpenSSL::OpenSSLError => e
      raise Error.new(e.message)
    end
1090311
function _setupInlineCrypt()
    {
        $lambda_functions =& self::_getLambdaFunctions();

        // Max. 10 Ultra-Hi-optimized inline-crypt functions. After that, we'll (still) create very fast code, but not the ultimate fast one.
        // (Currently, for Crypt_Twofish, one generated $lambda_function cost on php5.5@32bit ~140kb unfreeable mem and ~240kb on php5.5@64bit)
        $gen_hi_opt_code = (bool)(count($lambda_functions) < 10);

        // Generation of a unique hash for our generated code
        $code_hash = "Crypt_Twofish, {$this->mode}";
        if ($gen_hi_opt_code) {
            $code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key);
        }

        $safeint = $this->safe_intval_inline();

        if (!isset($lambda_functions[$code_hash])) {
            switch (true) {
                case $gen_hi_opt_code:
                    $K = $this->K;
                    $init_crypt = '
                        static $S0, $S1, $S2, $S3;
                        if (!$S0) {
                            for ($i = 0; $i < 256; ++$i) {
                                $S0[] = (int)$self->S0[$i];
                                $S1[] = (int)$self->S1[$i];
                                $S2[] = (int)$self->S2[$i];
                                $S3[] = (int)$self->S3[$i];
                            }
                        }
                    ';
                    break;
                default:
                    $K   = array();
                    for ($i = 0; $i < 40; ++$i) {
                        $K[] = '$K_' . $i;
                    }
                    $init_crypt = '
                        $S0 = $self->S0;
                        $S1 = $self->S1;
                        $S2 = $self->S2;
                        $S3 = $self->S3;
                        list(' . implode(',', $K) . ') = $self->K;
                    ';
            }

            // Generating encrypt code:
            $encrypt_block = '
                $in = unpack("V4", $in);
                $R0 = '.$K[0].' ^ $in[1];
                $R1 = '.$K[1].' ^ $in[2];
                $R2 = '.$K[2].' ^ $in[3];
                $R3 = '.$K[3].' ^ $in[4];
            ';
            for ($ki = 7, $i = 0; $i < 8; ++$i) {
                $encrypt_block.= '
                    $t0 = $S0[ $R0        & 0xff] ^
                          $S1[($R0 >>  8) & 0xff] ^
                          $S2[($R0 >> 16) & 0xff] ^
                          $S3[($R0 >> 24) & 0xff];
                    $t1 = $S0[($R1 >> 24) & 0xff] ^
                          $S1[ $R1        & 0xff] ^
                          $S2[($R1 >>  8) & 0xff] ^
                          $S3[($R1 >> 16) & 0xff];
                    $R2^= ' . sprintf($safeint, '$t0 + $t1 + ' . $K[++$ki]) . ';
                    $R2 = ($R2 >> 1 & 0x7fffffff) | ($R2 << 31);
                    $R3 = ((($R3 >> 31) & 1) | ($R3 << 1)) ^ ' . sprintf($safeint, '($t0 + ($t1 << 1) + ' . $K[++$ki] . ')') . ';

                    $t0 = $S0[ $R2        & 0xff] ^
                          $S1[($R2 >>  8) & 0xff] ^
                          $S2[($R2 >> 16) & 0xff] ^
                          $S3[($R2 >> 24) & 0xff];
                    $t1 = $S0[($R3 >> 24) & 0xff] ^
                          $S1[ $R3        & 0xff] ^
                          $S2[($R3 >>  8) & 0xff] ^
                          $S3[($R3 >> 16) & 0xff];
                    $R0^= ' . sprintf($safeint, '($t0 + $t1 + ' . $K[++$ki] . ')') . ';
                    $R0 = ($R0 >> 1 & 0x7fffffff) | ($R0 << 31);
                    $R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ ' . sprintf($safeint, '($t0 + ($t1 << 1) + ' . $K[++$ki] . ')') . ';
                ';
            }
            $encrypt_block.= '
                $in = pack("V4", ' . $K[4] . ' ^ $R2,
                                 ' . $K[5] . ' ^ $R3,
                                 ' . $K[6] . ' ^ $R0,
                                 ' . $K[7] . ' ^ $R1);
            ';

            // Generating decrypt code:
            $decrypt_block = '
                $in = unpack("V4", $in);
                $R0 = '.$K[4].' ^ $in[1];
                $R1 = '.$K[5].' ^ $in[2];
                $R2 = '.$K[6].' ^ $in[3];
                $R3 = '.$K[7].' ^ $in[4];
            ';
            for ($ki = 40, $i = 0; $i < 8; ++$i) {
                $decrypt_block.= '
                    $t0 = $S0[$R0       & 0xff] ^
                          $S1[$R0 >>  8 & 0xff] ^
                          $S2[$R0 >> 16 & 0xff] ^
                          $S3[$R0 >> 24 & 0xff];
                    $t1 = $S0[$R1 >> 24 & 0xff] ^
                          $S1[$R1       & 0xff] ^
                          $S2[$R1 >>  8 & 0xff] ^
                          $S3[$R1 >> 16 & 0xff];
                    $R3^= ' . sprintf($safeint, '$t0 + ($t1 << 1) + ' . $K[--$ki]) . ';
                    $R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31;
                    $R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ ' . sprintf($safeint, '($t0 + $t1 + '.$K[--$ki] . ')') . ';

                    $t0 = $S0[$R2       & 0xff] ^
                          $S1[$R2 >>  8 & 0xff] ^
                          $S2[$R2 >> 16 & 0xff] ^
                          $S3[$R2 >> 24 & 0xff];
                    $t1 = $S0[$R3 >> 24 & 0xff] ^
                          $S1[$R3       & 0xff] ^
                          $S2[$R3 >>  8 & 0xff] ^
                          $S3[$R3 >> 16 & 0xff];
                    $R1^= ' . sprintf($safeint, '$t0 + ($t1 << 1) + ' . $K[--$ki]) . ';
                    $R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31;
                    $R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ ' . sprintf($safeint, '($t0 + $t1 + '.$K[--$ki] . ')') . ';
                ';
            }
            $decrypt_block.= '
                $in = pack("V4", ' . $K[0] . ' ^ $R2,
                                 ' . $K[1] . ' ^ $R3,
                                 ' . $K[2] . ' ^ $R0,
                                 ' . $K[3] . ' ^ $R1);
            ';

            $lambda_functions[$code_hash] = $this->_createInlineCryptFunction(
                array(
                   'init_crypt'    => $init_crypt,
                   'init_encrypt'  => '',
                   'init_decrypt'  => '',
                   'encrypt_block' => $encrypt_block,
                   'decrypt_block' => $decrypt_block
                )
            );
        }
        $this->inline_crypt = $lambda_functions[$code_hash];
    }
996254
def decrypt(self, text, app_id):
        
        text = to_binary(text)
        decryptor = self.cipher.decryptor()
        plain_text = decryptor.update(base64.b64decode(text)
                                      ) + decryptor.finalize()

        padding = byte2int(plain_text, -1)
        content = plain_text[16:-padding]

        xml_len = socket.ntohl(struct.unpack("I", content[:4])[0])
        xml_content = content[4:xml_len + 4]
        from_appid = content[xml_len + 4:]

        if to_text(from_appid) != app_id:
            raise AppIdValidationError(text, app_id)

        return xml_content