Return the properly formatted ssh value for the authorized encryption key
    type. ecdsa defaults to 256 bits, must give full ecdsa enc schema string
    if using higher enc. If the type is not found, raise CommandExecutionError.
546672
def _refine_enc(enc):
    '''
    
    '''

    rsa = ['r', 'rsa', 'ssh-rsa']
    dss = ['d', 'dsa', 'dss', 'ssh-dss']
    ecdsa = ['e', 'ecdsa', 'ecdsa-sha2-nistp521', 'ecdsa-sha2-nistp384',
             'ecdsa-sha2-nistp256']
    ed25519 = ['ed25519', 'ssh-ed25519']

    if enc in rsa:
        return 'ssh-rsa'
    elif enc in dss:
        return 'ssh-dss'
    elif enc in ecdsa:
        # ecdsa defaults to ecdsa-sha2-nistp256
        # otherwise enc string is actual encoding string
        if enc in ['e', 'ecdsa']:
            return 'ecdsa-sha2-nistp256'
        return enc
    elif enc in ed25519:
        return 'ssh-ed25519'
    else:
        raise CommandExecutionError(
            'Incorrect encryption key type \'{0}\'.'.format(enc)
        )
1021520
def rfc6979_ecdsa_nonce(hash, privkey)
      raise ArgumentError, "Hash must be 32 bytes long" if hash.bytesize != 32
      raise ArgumentError, "Private key must be 32 bytes long" if privkey.bytesize != 32

      autorelease do |pool|
        order = self.group_order

        # Step 3.2.a. hash = H(message). Already performed by the caller.

        # Step 3.2.b. V = 0x01 0x01 0x01 ... 0x01 (32 bytes equal 0x01)
        v = "\x01".b*32

        # Step 3.2.c. K = 0x00 0x00 0x00 ... 0x00 (32 bytes equal 0x00)
        k = "\x00".b*32

        # Step 3.2.d. K = HMAC-SHA256(key: K, data: V || 0x00 || int2octets(privkey) || bits2octets(hash))
        h1 = pool.new_bn(hash)
        BN_div(nil, h1, h1, order, pool.bn_ctx) # h1 = h1 % order
        h1data = data_from_bn(h1, min_length: 32)
        k = BTC.hmac_sha256(key: k, data: v + "\x00".b + privkey + h1data)

        # Step 3.2.e. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.f. K = HMAC-SHA256(key: K, data: V || 0x01 || int2octets(privkey) || bits2octets(hash))
        k = BTC.hmac_sha256(key: k, data: v + "\x01".b + privkey + h1data)

        # Step 3.2.g. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.h.
        zero32 = "\x00".b*32
        10000.times do
          t = BTC.hmac_sha256(key: k, data: v)
          tn = pool.new_bn(t)
          if BN_cmp(tn, order) < 0
            nonce = data_from_bn(tn, min_length: 32)
            if nonce != zero32
              return nonce
            end
          end
          # Note: the probability of not succeeding at the first try is about 2^-127.
          k = BTC.hmac_sha256(key: k, data: v + zero32)
          v = BTC.hmac_sha256(key: k, data: v)
        end
        # we generated 10000 numbers, none of them is good -> fail.
        raise "Cannot find any good ECDSA nonce after 10000 iterations of RFC6979."
      end
    end
835472
def x5t_calculation(cert):
    
    if isinstance(cert, str):
        der_cert = base64.b64decode(cert.encode('ascii'))
    else:
        der_cert = base64.b64decode(cert)

    return b64e(hashlib.sha1(der_cert).digest())
953413
def generate_signing_key(args):
    
    if os.path.exists(args.keyfile):
        raise esptool.FatalError("ERROR: Key file %s already exists" % args.keyfile)
    sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
    with open(args.keyfile, "wb") as f:
        f.write(sk.to_pem())
    print("ECDSA NIST256p private key in PEM format written to %s" % args.keyfile)
428035
def verify(self, h, sig, sig_fmt=SER_BINARY):
        
        s = deserialize_number(sig, sig_fmt)
        return self.p._ECDSA_verify(h, s)
295188
def calculate_authentication_data(self, key):
        '''
        
        '''
        # This one is easy
        if self.key_id == KEY_ID_NONE:
            return ''

        # Determine the digestmod and how long the authentication data will be
        if self.key_id == KEY_ID_HMAC_SHA_1_96:
            digestmod = hashlib.sha1
            data_length = 20
        elif self.key_id == KEY_ID_HMAC_SHA_256_128:
            digestmod = hashlib.sha256
            data_length = 32
        else:
            raise ValueError('Unknown Key ID')

        # Fill the authentication data with the right number of zeroes
        # after storing the original first so we can restore it later
        current_authentication_data = self.authentication_data
        self.authentication_data = '\x00' * data_length

        # Build the packet
        msg = self.to_bytes()

        # Restore the authentication data
        self.authentication_data = current_authentication_data

        # Return the authentication data based on the generated packet
        # and the given key
        return hmac.new(key, msg, digestmod).digest()
889234
def create_ecdsap256_key_pair():
    
    pub  = ECDSAP256PublicKey()
    priv = ECDSAP256PrivateKey()
    rc = _lib.xtt_crypto_create_ecdsap256_key_pair(pub.native, priv.native)
    if rc == RC.SUCCESS:
        return (pub, priv)
    else:
        raise error_from_code(rc)
628108
def extract_public_key(args):
    
    sk = _load_ecdsa_signing_key(args)
    vk = sk.get_verifying_key()
    args.public_keyfile.write(vk.to_string())
    print("%s public key extracted to %s" % (args.keyfile.name, args.public_keyfile.name))
416295
def private_key_from_der_format(der_key)
      raise ArgumentError, "Missing DER private key" if !der_key

      prepare_if_needed

      buf = FFI::MemoryPointer.from_string(der_key)
      ec_key = d2i_ECPrivateKey(nil, pointer_to_pointer(buf), buf.size-1)
      if ec_key.null?
        raise BTCError, "OpenSSL failed to create EC_KEY with DER private key"
      end
      bn = EC_KEY_get0_private_key(ec_key)
      BN_bn2bin(bn, buf)
      buf.read_string(32)
    end
244108
def get(key, default=-1):
        """"""
        if isinstance(key, int):
            return ECDSA_LOW_Curve(key)
        if key not in ECDSA_LOW_Curve._member_map_:
            extend_enum(ECDSA_LOW_Curve, key, default)
        return ECDSA_LOW_Curve[key]
154363
def encryption_mode(self):
        

        encryption_algo = self['algorithm'].native

        if encryption_algo[0:7] in set(['aes128_', 'aes192_', 'aes256_']):
            return encryption_algo[7:]

        if encryption_algo[0:6] == 'pbes1_':
            return 'cbc'

        if encryption_algo[0:7] == 'pkcs12_':
            return 'cbc'

        if encryption_algo in set(['des', 'tripledes_3key', 'rc2', 'rc5']):
            return 'cbc'

        if encryption_algo == 'pbes2':
            return self['parameters']['encryption_scheme'].encryption_mode

        raise ValueError(unwrap(
            '''
            Unrecognized encryption algorithm "%s"
            ''',
            encryption_algo
        ))
562356
def secp256k1():
        
        GFp = FiniteField(2 ** 256 - 2 ** 32 - 977)  # This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
        ec = EllipticCurve(GFp, 0, 7)
        return ECDSA(ec, ec.point(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8), 2 ** 256 - 432420386565659656852420866394968145599)
1034239
def ecdsa_signature(hash, privkey, normalized: true)
      raise ArgumentError, "Hash is missing" if !hash
      raise ArgumentError, "Private key is missing" if !privkey

      # ECDSA signature is a pair of numbers: (Kx, s)
      # Where Kx = x coordinate of k*G mod n (n is the order of secp256k1).
      # And s = (k^-1)*(h + Kx*privkey).
      # By default, k is chosen randomly on interval [0, n - 1].
      # But this makes signatures harder to test and allows faulty or
      # backdoored RNGs to leak private keys from ECDSA signatures.
      # To avoid these issues, we'll generate k = Hash256(hash || privatekey)
      # and make all computations by hand.

      autorelease do |pool|

        # Order of our curve
        n = self.group_order
        halfn = self.group_half_order

        # Generate k deterministically from private key and message using HMAC-SHA256
        # This is an important point #1.
        kdata = rfc6979_ecdsa_nonce(hash, privkey)
        k = pool.new_bn(kdata)

        # Enforce k within group order: k = k % n
        BN_div(nil, k, k, n, pool.bn_ctx)

        # Compute K = k*G
        #(can't use K variable name because Ruby does not allow
        # constant assignment in methods)
        kG = pool.new_ec_point
        EC_POINT_mul(self.group, kG, k, nil, nil, pool.bn_ctx)

        # Compute r = K.x. This is first half of the signature.
        r = pool.new_bn
        EC_POINT_get_affine_coordinates_GFp(self.group, kG, r, nil, pool.bn_ctx)

        # Compute s = (k^-1)*(h + r*privkey).
        h = pool.new_bn(hash)
        p = pool.new_bn(privkey)
        tmp = pool.new_bn
        s = pool.new_bn
        BN_mod_mul(tmp, r, p, n, pool.bn_ctx) # tmp = r*privkey
        BN_mod_add_quick(s, tmp, h, n)        # s = h + tmp = h + r*privkey
        BN_mod_inverse(k, k, n, pool.bn_ctx)  # k' = k^-1
        BN_mod_mul(s, s, k, n, pool.bn_ctx)   # s = k'*(h + r*privkey)

        # Enforce low S values, by negating the value (modulo the order) if above order/2.
        # This is an important point #2. Not doing that would yield (sometimes)
        # non-canonical signatures that will be rejected by many relaying nodes.
        if normalized
          if BN_cmp(s, halfn) > 0
            BN_sub(s, n, s)
          end
        end

        # Fill in ECDSA_SIG structure so we can convert it into a proper DER format.
        sig = ECDSA_SIG.new
        sig[:r] = r
        sig[:s] = s

        # Encode signature in DER format.

        sig_size = 72 # typical size of a signature (when both numbers are 33 bytes).

        # allocate a bit more memory just in case (cargo cult)
        buffer = FFI::MemoryPointer.new(:uint8, sig_size + 16)
        sig_size = i2d_ECDSA_SIG(sig.pointer, pointer_to_pointer(buffer))

        # read actual number of bytes composed by OpenSSL
        signature = buffer.read_string(sig_size)
        signature
      end
    end
1194800
def encrypt(self, paddedPlaintext):
        
        # TODO: make this less ugly and python 2 and 3 compatible
        # paddedMessage = bytearray(paddedMessage.encode() if (sys.version_info >= (3, 0) and not type(paddedMessage) in (bytes, bytearray)) or type(paddedMessage) is unicode else paddedMessage)
        if (sys.version_info >= (3, 0) and
                not type(paddedPlaintext) in (bytes, bytearray)) or type(paddedPlaintext) is unicode:
            paddedPlaintext = bytearray(paddedPlaintext.encode())
        else:
            paddedPlaintext = bytearray(paddedPlaintext)
        try:
            record = self.senderKeyStore.loadSenderKey(self.senderKeyName)
            senderKeyState = record.getSenderKeyState()
            senderKey = senderKeyState.getSenderChainKey().getSenderMessageKey()
            ciphertext = self.getCipherText(senderKey.getIv(), senderKey.getCipherKey(), paddedPlaintext)

            senderKeyMessage = SenderKeyMessage(senderKeyState.getKeyId(),
                                                senderKey.getIteration(),
                                                ciphertext,
                                                senderKeyState.getSigningKeyPrivate())

            senderKeyState.setSenderChainKey(senderKeyState.getSenderChainKey().getNext())
            self.senderKeyStore.storeSenderKey(self.senderKeyName, record)

            return senderKeyMessage.serialize()
        except InvalidKeyIdException as e:
            raise NoSessionException(e)
1019784
def create_key_pair(self, cert_type, bits):
        

        pkey = crypto.PKey()
        pkey.generate_key(cert_type, bits)
        return pkey
762825
def decode_auth_plain(ciphertext)
      message = begin
                  @ecc.ecies_decrypt ciphertext[0,307]
                rescue
                  raise AuthenticationError, $!
                end
      raise RLPxSessionError, 'invalid message length' unless message.size == 194

      sig = message[0,65]
      pubkey = message[65+32,64]
      raise InvalidKeyError, 'invalid initiator pubkey' unless Crypto::ECCx.valid_key?(pubkey)

      nonce = message[65+32+64,32]
      flag = message[(65+32+64+32)..-1].ord
      raise RLPxSessionError, 'invalid flag' unless flag == 0

      [307, sig, pubkey, nonce, 4]
    end
433816
def GetConsensusAddress(validators):
        
        vlen = len(validators)
        script = Contract.CreateMultiSigRedeemScript(vlen - int((vlen - 1) / 3), validators)
        return Crypto.ToScriptHash(script)