Convert private key in DER encoding to a Private key object

        :param data: private key bytes
        :param password: password the private key is encrypted with
330668
def from_der_private_key(data: bytes, password: Optional[str] = None) -> _RSAPrivateKey:
        
        return serialization.load_der_private_key(data, password, default_backend())
389608
function encrypt(data, key) {
    return Promise.resolve().then(function() {
        var bytesLeft = data.byteLength;
        var currentOffset = 0, blockIndex = 0, totalLength = 0;
        var buffers = [];

        var next = function() {
            var blockLength = Math.min(BlockSize, bytesLeft);
            bytesLeft -= blockLength;

            var blockData = data.slice(currentOffset, currentOffset + blockLength);
            return getBlockHmac(key, blockIndex, blockLength, blockData).then(function(blockHash) {
                var blockBuffer = new ArrayBuffer(32 + 4);
                var stm = new BinaryStream(blockBuffer);
                stm.writeBytes(blockHash);
                stm.setUint32(blockLength, true);

                buffers.push(blockBuffer);
                totalLength += blockBuffer.byteLength;

                if (blockData.byteLength > 0) {
                    buffers.push(blockData);
                    totalLength += blockData.byteLength;
                    blockIndex++;
                    currentOffset += blockLength;
                    return next();
                } else {
                    var ret = new Uint8Array(totalLength);
                    var offset = 0;
                    for (var i = 0; i < buffers.length; i++) {
                        ret.set(new Uint8Array(buffers[i]), offset);
                        offset += buffers[i].byteLength;
                    }
                    return ret.buffer;
                }
            });
        };
        return next();
    });
}
379265
def get_private(self):
        
        a = compat_bytes(self.account + self.role + self.password, 'utf8')
        s = hashlib.sha256(a).digest()
        return PrivateKey(hexlify(s).decode('ascii'))
1042088
def decrypt(data, opts={})
      data = data.to_s
      raise "No private key set!" unless @key.private?
      unless opts[:binary]
        data = Base64.decode64(data)
      end
      @key.private_decrypt(data)
    end
813038
function sign(private_key, data) {
  var key = new bitcoinjs.ECKey(new BigInteger(private_key, 16), false);
  var hash = bitcoinjs.crypto.hash256(new Buffer(data, 'hex'));
  return key.sign(hash).toDER().toString('hex');
}
993775
public static String decryptByPrivateKey(String data, String privateKey, String fillMode) throws Exception {
		byte[] encryptedData = base64.decode(data);
		byte[] keyBytes = base64.decode(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		// Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		Cipher cipher = Cipher.getInstance(fillMode);

		cipher.init(Cipher.DECRYPT_MODE, privateK);
		int inputLen = encryptedData.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();
		return new String(decryptedData);
	}
787853
def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None,
            region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        ciphertext = conn.encrypt(
            key_id,
            plaintext,
            encryption_context=encryption_context,
            grant_tokens=grant_tokens
        )
        r['ciphertext'] = ciphertext['CiphertextBlob']
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r
276689
def _encrypt(data):
    """"""
    BS = AES.block_size

    def pad(s):
        n = BS - len(s) % BS
        char = chr(n).encode('utf8')
        return s + n * char

    password = settings.GECKOBOARD_PASSWORD
    salt = Random.new().read(BS - len('Salted__'))
    key, iv = _derive_key_and_iv(password, salt, 32, BS)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    encrypted = b'Salted__' + salt + cipher.encrypt(pad(data))
    return base64.b64encode(encrypted)
1320618
def privatekey_to_publickey(private_key_bin: bytes) -> bytes:
    
    if not ishash(private_key_bin):
        raise ValueError('private_key_bin format mismatch. maybe hex encoded?')
    return keys.PrivateKey(private_key_bin).public_key.to_bytes()
414570
def encrypt(data, raw_pubkey)
      raise ArgumentError, "invalid pubkey of length #{raw_pubkey.size}" unless raw_pubkey.size == 64
      Crypto::ECIES.encrypt data, raw_pubkey
    end
1039835
def serialize_private_key_to_pem(private_key, passphrase_bytes=None):
    
    return private_key.private_bytes(
        encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM,
        format=cryptography.hazmat.primitives.serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=cryptography.hazmat.primitives.serialization.BestAvailableEncryption(
            passphrase_bytes
        )
        if passphrase_bytes is not None
        else cryptography.hazmat.primitives.serialization.NoEncryption(),
    )
673635
def decrypt(private, ciphertext, output):
    
    privatekeydata = json.load(private)
    assert 'pub' in privatekeydata
    pub = load_public_key(privatekeydata['pub'])

    log("Loading private key")
    private_key_error = "Invalid private key"
    assert 'key_ops' in privatekeydata, private_key_error
    assert "decrypt" in privatekeydata['key_ops'], private_key_error
    assert 'p' in privatekeydata, private_key_error
    assert 'q' in privatekeydata, private_key_error
    assert privatekeydata['kty'] == 'DAJ', private_key_error

    _p = phe.util.base64_to_int(privatekeydata['p'])
    _q = phe.util.base64_to_int(privatekeydata['q'])

    private_key = phe.PaillierPrivateKey(pub, _p, _q)

    log("Decrypting ciphertext")
    enc = load_encrypted_number(ciphertext, pub)
    out = private_key.decrypt(enc)
    print(out, file=output)
1255056
public function encryptByPrivateKey_data($data, $privatekey = '')
	{
		$RSACrypt = new RSACrypt();

		if ($privatekey != "") {
			$RSACrypt->privkey = $privatekey;
		}
		$crypt_res = "";
		for ($i = 0; $i < ((strlen($data) - strlen($data) % 117) / 117 + 1); $i++) {
			$crypt_res = $crypt_res . ($RSACrypt->encryptByPrivateKey(mb_strcut($data, $i * 117, 117, 'utf-8')));
		}
		return $crypt_res;
	}
1333897
def rsa_decrypt(encrypted_data, pem, password=None):
    
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import padding

    encrypted_data = to_binary(encrypted_data)
    pem = to_binary(pem)
    private_key = serialization.load_pem_private_key(pem, password, backend=default_backend())
    data = private_key.decrypt(
        encrypted_data,
        padding=padding.OAEP(
            mgf=padding.MGF1(hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None,
        )
    )
    return data
555930
def get_private_key(key_path, password_path=None):
    """"""

    assert key_path, key_path
    if not os.path.exists(key_path):
        log.fatal('%s: no such file', key_path)
        return None

    if not check_permission_safety(key_path):
        log.fatal('Private key file %s must be readable only by its owner.', key_path)
        return None

    if password_path and not check_permission_safety(password_path):
        log.fatal('Password file %s must be readable only by its owner.', password_path)
        return None

    with open(key_path) as keyfile:
        private_key = keyfile.readline().strip()

        if is_hex(private_key) and len(decode_hex(private_key)) == 32:
            log.warning('Private key in raw format. Consider switching to JSON-encoded')
        else:
            keyfile.seek(0)
            try:
                json_data = json.load(keyfile)
                if password_path:
                    with open(password_path) as password_file:
                        password = password_file.readline().strip()
                else:
                    password = getpass.getpass('Enter the private key password: ')
                if json_data['crypto']['kdf'] == 'pbkdf2':
                    password = password.encode()  # type: ignore
                private_key = encode_hex(decode_keyfile_json(json_data, password))
            except ValueError:
                log.fatal('Invalid private key format or password!')
                return None

    return private_key
1256586
def encrypt(self, data):
        
        if False in six.itervalues(self.ready):
            raise CipherError(data)
        encryptor = self._cipher.encryptor()
        tmp = encryptor.update(data) + encryptor.finalize()
        self.iv = tmp[-self.block_size:]
        return tmp
247958
def load_key(self, key, key_type, key_encoding):
        
        if key_type not in (EncryptionKeyType.PRIVATE, EncryptionKeyType.PUBLIC):
            raise ValueError(
                'Invalid key type "{key_type}" for cipher "{cipher}"'.format(key_type=key_type, cipher=self.java_name)
            )

        if key_encoding not in (KeyEncodingType.DER, KeyEncodingType.PEM):
            raise ValueError(
                'Invalid key encoding "{key_encoding}" for cipher "{cipher}"'.format(
                    key_encoding=key_encoding, cipher=self.java_name
                )
            )

        return _KEY_LOADERS[self.cipher](key, key_type, key_encoding)