rsa 加密
    :param data: 待加密字符串/binary
    :param pem: RSA public key 内容/binary
    :param b64_encode: 是否对输出进行 base64 encode
    :return: 如果 b64_encode=True 的话，返回加密并 base64 处理后的 string；否则返回加密后的 binary
773434
def rsa_encrypt(data, pem, b64_encode=True):
    
    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
    encoded_data = to_binary(data)
    pem = to_binary(pem)
    public_key = serialization.load_pem_public_key(pem, backend=default_backend())
    encrypted_data = public_key.encrypt(
        encoded_data,
        padding=padding.OAEP(
            mgf=padding.MGF1(hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None,
        )
    )
    if b64_encode:
        encrypted_data = base64.b64encode(encrypted_data).decode('utf-8')
    return encrypted_data
674672
function encryptChunk(data) {
  try {
    var encryptedBytes = this.__key.encrypt(data, 'RSAES-PKCS1-V1_5');
    var encryptedBase64 = btoa(encryptedBytes);
    return encryptedBase64;
  } catch(e) {
    return e;
  }
}
743408
public function decodePEM($pem_data)
    {
        $pem_data = $this->pemDataClean($pem_data);
        $decoded  = bin2hex(base64_decode($pem_data));

        $this->pemDataLenCheck($decoded);

        $ecpemstruct = array(
                             'oct_sec_val'  => substr($decoded, 14, 64),
                             'obj_id_val'   => substr($decoded, 86, 10),
                             'bit_str_val'  => substr($decoded, 106),
                            );

        $this->pemOidCheck($ecpemstruct['obj_id_val']);

        $private_key = $ecpemstruct['oct_sec_val'];
        $public_key  = '04' . $ecpemstruct['bit_str_val'];

        $this->pemKeyLenCheck(array($private_key, $public_key));

        return array(
                     'private_key' => $private_key,
                     'public_key'  => $public_key
                    );
    }
181025
def create_binary_security_token(key_file):
    
    node = etree.Element(
        ns_id('BinarySecurityToken', ns.wssens),
        nsmap={ns.wssens[0]: ns.wssens[1]})
    node.set(ns_id('Id', ns.wsuns), get_unique_id())
    node.set('EncodingType', ns.wssns[1] + 'Base64Binary')
    node.set('ValueType', BINARY_TOKEN_TYPE)

    with open(key_file) as fh:
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, fh.read())
        node.text = base64.b64encode(
            crypto.dump_certificate(crypto.FILETYPE_ASN1, cert))
    return node
302371
public String encryptBase64(String data, KeyType keyType) {
		return Base64.encode(encrypt(data, keyType));
	}
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(),
    )
1238364
def Decode(self, encoded_data):
    
    try:
      decoded_data = base64.b32decode(encoded_data, casefold=False)
    except (TypeError, binascii.Error) as exception:
      raise errors.BackEndError(
          'Unable to decode base32 stream with error: {0!s}.'.format(
              exception))

    return decoded_data, b''
1191541
def process_pem_rsakey(self, data, name, idx):
        
        from cryptography.hazmat.primitives.serialization import load_der_public_key
        from cryptography.hazmat.primitives.serialization import load_der_private_key
        try:
            if startswith(data, '-----BEGIN RSA PUBLIC KEY') or startswith(data, '-----BEGIN PUBLIC KEY'):
                rsa = load_der_public_key(pem_to_der(data), self.get_backend())
                public_numbers = rsa.public_numbers()
            elif startswith(data, '-----BEGIN RSA PRIVATE KEY') or startswith(data, '-----BEGIN PRIVATE KEY'):
                rsa = load_der_private_key(pem_to_der(data), None, self.get_backend())
                public_numbers = rsa.private_numbers().public_numbers
            else:
                return None
            self.num_rsa_keys += 1
            self.num_rsa += 1

            js = collections.OrderedDict()
            js['type'] = 'pem-rsa-key'
            js['fname'] = name
            js['idx'] = idx
            js['pem'] = data
            js['e'] = '0x%x' % public_numbers.e
            js['n'] = '0x%x' % public_numbers.n

            if self.has_fingerprint(public_numbers.n):
                logger.warning('Fingerprint found in PEM RSA key %s ' % name)
                self.mark_and_add_effort(public_numbers.n, js)

                if self.do_print:
                    print(json.dumps(js))

            return TestResult(js)

        except Exception as e:
            logger.debug('Pubkey loading error: %s : %s [%s] : %s' % (name, idx, data[:20], e))
            self.trace_logger.log(e)
471646
def sign(self, data, b64=True):
        
        padder = padding.PKCS1v15()
        signer = self.private_key.signer(padder, None)
        if not isinstance(data, six.binary_type):
            data = data.encode('utf_8')
        signer.update(data)
        signed = signer.finalize()
        if b64:
            signed = base64.b64encode(signed)
        return signed
1246226
def _b64encode_to_str(data):
    
    ret = b64encode(data)
    if not isinstance(ret, str):  # Python3
        return ret.decode('ascii')
    else:
        return ret
804578
static String base64(byte[] data) {
        ByteBuf encodedData = Unpooled.wrappedBuffer(data);
        ByteBuf encoded = Base64.encode(encodedData);
        String encodedString = encoded.toString(CharsetUtil.UTF_8);
        encoded.release();
        return encodedString;
    }
128146
def import_public_rsa_key_from_file(filename):
    
    with open(filename, "rb") as key_file:
        public_key = serialization.load_pem_public_key(
            key_file.read(),
            backend=default_backend())
    return public_key
951069
private static byte[] sha256(byte[] data) {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance(ALGORITHM_SHA256);
			md.reset();
			md.update(data);
			return md.digest();
		} catch (Exception e) {
			LogUtil.writeErrorLog("SHA256计算失败", e);
			return null;
		}
	}
393967
def encode(self, b64=False, always_bytes=True):
        """"""
        if self.binary and not b64:
            encoded_packet = six.int2byte(self.packet_type)
        else:
            encoded_packet = six.text_type(self.packet_type)
            if self.binary and b64:
                encoded_packet = 'b' + encoded_packet
        if self.binary:
            if b64:
                encoded_packet += base64.b64encode(self.data).decode('utf-8')
            else:
                encoded_packet += self.data
        elif isinstance(self.data, six.string_types):
            encoded_packet += self.data
        elif isinstance(self.data, dict) or isinstance(self.data, list):
            encoded_packet += self.json.dumps(self.data,
                                              separators=(',', ':'))
        elif self.data is not None:
            encoded_packet += str(self.data)
        if always_bytes and not isinstance(encoded_packet, binary_types):
            encoded_packet = encoded_packet.encode('utf-8')
        return encoded_packet
335691
def load_key(pubkey):
    
    try:
        return load_pem_public_key(pubkey.encode(), default_backend())
    except ValueError:
        # workaround for https://github.com/travis-ci/travis-api/issues/196
        pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END')
        return load_pem_public_key(pubkey.encode(), default_backend())
245315
private byte[] cipherData(final byte[] data) {
        byte[] result = null;
        try {
            final byte[] buffer = new byte[this.paddedBufferedBlockCipher.getOutputSize(data.length)];

            final int processedBytes = this.paddedBufferedBlockCipher.processBytes(data, 0, data.length, buffer, 0);
            final int finalBytes = this.paddedBufferedBlockCipher.doFinal(buffer, processedBytes);

            result = new byte[processedBytes + finalBytes];
            System.arraycopy(buffer, 0, result, 0, result.length);
        } catch (final CryptoException e) {
            LOG.error("Failed to encrypt/decrypt data array", e);
        }

        return result;
    }
707325
private byte[] maybeDecodeBase64(byte[] byteArray) {
    try {
      String pem = new String(byteArray);
      // Remove required begin/end lines.
      pem = pem.substring(BEGIN_CERT_LINE_LENGTH, pem.length() - END_CERT_LINE_LENGTH);
      return Base64.getDecoder().decode(pem);
    } catch (Exception e) {
      // Not a valid PEM encoded certificate, return original array.
      return byteArray;
    }
  }