BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.
334652
def encrypt(cls, crypto, privkey, passphrase):
        
        pub_byte, priv_byte = get_magic_bytes(crypto)
        privformat = get_privkey_format(privkey)
        if privformat in ['wif_compressed','hex_compressed']:
            compressed = True
            flagbyte = b'\xe0'
            if privformat == 'wif_compressed':
                privkey = encode_privkey(privkey, 'hex_compressed')
                privformat = get_privkey_format(privkey)
        if privformat in ['wif', 'hex']:
            compressed = False
            flagbyte = b'\xc0'
        if privformat == 'wif':
            privkey = encode_privkey(privkey,'hex')
            privformat = get_privkey_format(privkey)

        pubkey = privtopub(privkey)
        addr = pubtoaddr(pubkey, pub_byte)

        passphrase = normalize('NFC', unicode(passphrase))
        if is_py2:
            ascii_key = addr
            passphrase = passphrase.encode('utf8')
        else:
            ascii_key = bytes(addr,'ascii')

        salt = sha256(sha256(ascii_key).digest()).digest()[0:4]
        key = scrypt.hash(passphrase, salt, 16384, 8, 8)
        derivedhalf1, derivedhalf2 = key[:32], key[32:]

        aes = AES.new(derivedhalf2)
        encryptedhalf1 = aes.encrypt(unhexlify('%0.32x' % (long(privkey[0:32], 16) ^ long(hexlify(derivedhalf1[0:16]), 16))))
        encryptedhalf2 = aes.encrypt(unhexlify('%0.32x' % (long(privkey[32:64], 16) ^ long(hexlify(derivedhalf1[16:32]), 16))))

        # 39 bytes    2 (6P)      1(R/Y)    4          16               16
        payload = b'\x01\x42' + flagbyte + salt + encryptedhalf1 + encryptedhalf2
        return cls(crypto, b58encode_check(payload))
1173867
def encrypt(self, password):
        
        if not password or not self._crypter:
            return password or b''
        return self._crypter.encrypt(password)
960670
def PrivateKeyFromWIF(wif):
        
        if wif is None or len(wif) is not 52:
            raise ValueError('Please provide a wif with a length of 52 bytes (LEN: {0:d})'.format(len(wif)))

        data = base58.b58decode(wif)

        length = len(data)

        if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01:
            raise ValueError("Invalid format!")

        checksum = Crypto.Hash256(data[0:34])[0:4]

        if checksum != data[34:]:
            raise ValueError("Invalid WIF Checksum!")

        return data[1:33]
1195835
def DecryptPrivateKey(self, encrypted_private_key):
        
        aes = AES.new(self._master_key, AES.MODE_CBC, self._iv)
        return aes.decrypt(encrypted_private_key)
1285786
def load_key(self, key):
        

        self._serialize(key)
        if isinstance(key, rsa.RSAPrivateKey):
            self.priv_key = key
            self.pub_key = key.public_key()
        else:
            self.pub_key = key

        return self
100639
def public_key_from_ed25519_key(hex_public_key):
    """"""
    public_key = crypto.Ed25519VerifyingKey(bytes.fromhex(hex_public_key), encoding='bytes')
    return public_key.encode(encoding='base58').decode('utf-8')
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
        ))
520016
public static BigInteger publicKeyFromPrivate(BigInteger privKey) {
        ECPoint point = publicPointFromPrivate(privKey);

        byte[] encoded = point.getEncoded(false);
        return new BigInteger(1, Arrays.copyOfRange(encoded, 1, encoded.length));  // remove prefix
    }
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)
771038
def encrypt_with_import_key(self, plain):
        

        n, e = TemplateProcessor.read_serialized_rsa_pub_key(self.import_key['key'])
        n_bit_size = long_bit_size(n)
        bs = 0
        if n_bit_size > 1024-10 and n_bit_size < 1024+10:
            bs = 128
        elif n_bit_size > 2048-10 and n_bit_size < 2048+10:
            bs = 256
        else:
            raise CryptoError('Unknown RSA modulus size: %d', n_bit_size)

        padded = PKCS15.pad(plain, bs=bs, bt=2)
        return rsa_enc(padded, n, e)
1231689
def encrypted_gradient(self, sum_to=None):
        
        gradient = self.compute_gradient()
        encrypted_gradient = encrypt_vector(self.pubkey, gradient)

        if sum_to is not None:
            return sum_encrypted_vectors(sum_to, encrypted_gradient)
        else:
            return encrypted_gradient
1103430
def schnorr_generate_nonce_pair(self, msg, raw=False,
                                    digest=hashlib.sha256):
        
        if not HAS_SCHNORR:
            raise Exception("secp256k1_schnorr not enabled")

        msg32 = _hash32(msg, raw, digest)
        pubnonce = ffi.new('secp256k1_pubkey *')
        privnonce = ffi.new('char [32]')

        valid = lib.secp256k1_schnorr_generate_nonce_pair(
            self.ctx, pubnonce, privnonce, msg32, self.private_key,
            ffi.NULL, ffi.NULL)
        assert valid == 1

        return pubnonce, privnonce
880109
async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
        

        random_bytes = os.urandom(32)

        padder = PKCS7(AES.block_size).padder()
        padded_result = await self._loop.run_in_executor(
            None, lambda: (padder.update(random_bytes) + padder.finalize()))

        aesecb = self._cipher.encryptor()
        encrypted_result = await self._loop.run_in_executor(
            None, lambda: (aesecb.update(padded_result) + aesecb.finalize()))

        return random_bytes, {}, base64.b64encode(encrypted_result).decode()
404129
function privKeyToPubKey(privKey, toCompressed) {
  toCompressed = toCompressed || false;

  const pkBuffer = Buffer.from(privKey, 'hex');
  var publicKey = secp256k1.publicKeyCreate(pkBuffer, toCompressed);
  return publicKey.toString('hex');
}
415663
async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
        
        if self.public_key is None:
            raise ValueError('Public key not provided during initialisation, cannot encrypt key encrypting key')

        random_bytes = os.urandom(32)

        ciphertext = await self._loop.run_in_executor(
            None, lambda: (self.public_key.encrypt(random_bytes, padding.PKCS1v15())))

        return random_bytes, {}, base64.b64encode(ciphertext).decode()
451759
def to_curve25519_private_key(self):
        
        sk = self._signing_key
        raw_private = nacl.bindings.crypto_sign_ed25519_sk_to_curve25519(sk)
        return _Curve25519_PrivateKey(raw_private)
749656
def _get_encryption_key():
    ''''''
    # initialize ENCRYPTION_KEY the first time it is needed, so that
    # applications that use eulcore without using this specific
    # functionality do not get bogus warnings about SECRET_KEY size.
    global ENCRYPTION_KEY
    if ENCRYPTION_KEY is None:
        # NOTE: Blowfish key length is variable but must be 32-448 bits
        # (but PyCrypto does not actually make this information accessible)
        KEY_MIN_CHARS = 32/8
        KEY_MAX_CHARS = 448/8
        if KEY_MIN_CHARS <= len(settings.SECRET_KEY) <= KEY_MAX_CHARS:
            ENCRYPTION_KEY = settings.SECRET_KEY
        else:
            ENCRYPTION_KEY = hashlib.sha224(settings.SECRET_KEY).hexdigest()
            message = '''Django secret key (current length of %d) requires hashing for use as encryption key
            (to avoid hashing, should be %d-%d characters)''' % \
            (len(settings.SECRET_KEY), KEY_MIN_CHARS, KEY_MAX_CHARS)
            logger.warn(message)
    return ENCRYPTION_KEY