RSA签名

@param $data 待签名数据
@param $private_key_path 商户私钥文件路径
@return string 签名结果
163523
public function createSign($data, $private_key_path)
    {
        $priKey = file_get_contents($private_key_path);
        $res = openssl_get_privatekey($priKey);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        //base64编码
        $sign = base64_encode($sign);
        return $sign;
    }
496784
protected function signature(string $decoded_query_string)
    {
        // 优先使用私钥路径，否则取私钥值
        if ($this->alipay_app_private_key_path) {
            $private_key = file_get_contents( $this->alipay_app_private_key_path );
        } else {
            $private_key =
                "-----BEGIN RSA PRIVATE KEY-----\n" .
                $this->alipay_app_private_key .
                "\n-----END RSA PRIVATE KEY-----";
        }

        $resource = openssl_get_privatekey($private_key);

        openssl_sign($decoded_query_string, $signature, $resource);

        $signature = base64_encode($signature);

        return $signature;
    }
489226
def import_rsa_key(pem_data):
    
    if not pem_data.startswith(PREFIX):
        pem_data = bytes('{}\n{}\n{}'.format(PREFIX, pem_data, POSTFIX),
                         'utf-8')
    else:
        pem_data = bytes(pem_data, 'utf-8')
    cert = x509.load_pem_x509_certificate(pem_data, default_backend())
    return cert.public_key()
154077
public  function decryptByPublicKey($data) {
		$pu_key =  openssl_pkey_get_public($this->pubkey);
		$decrypted = "";
		$data = self::urlsafe_b64decode($data);

		openssl_public_decrypt($data,$decrypted,$pu_key);//公钥解密

		return $decrypted;
	}
1174841
public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
        String keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes.getBytes());
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        setData(data, cipher, inputLen, out, offSet, i);

        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }
925167
def _get_private_key_obj(private_key, passphrase=None):
    '''
    
    '''
    private_key = _text_or_file(private_key)
    private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
    rsaprivkey = M2Crypto.RSA.load_key_string(
        private_key, callback=_passphrase_callback(passphrase))
    evpprivkey = M2Crypto.EVP.PKey()
    evpprivkey.assign_rsa(rsaprivkey)
    return evpprivkey
656762
public function decrypt($encrypted, $privateKey)
    {
        $rsa = new RSA();
        $rsa->loadKey($privateKey);

        return $rsa->decrypt($encrypted);
    }
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);
	}
321412
public function createX509Certificate($privateKey)
    {
        $rsa = new RSA();
        $rsa->loadKey($privateKey);

        $issuer = new X509();
        $issuer->setPrivateKey($rsa);
        $issuer->setDN($this->getDn());

        $csr = new X509();
        $csr->setPrivateKey($rsa);
        $csr->setDN($issuer->getDN());

        $csr = $csr->saveCSR($csr->signCSR());

        $subject = new X509();
        $subject->loadCSR($csr);

        $x509 = new X509();
        $x509->setEndDate($this->getCertificateValidity());

        return $x509->saveX509($x509->sign($issuer, $subject));
    }
1337907
public  function decryptByPrivateKey($data) {
		$pi_key =  openssl_pkey_get_private($this->privkey);
		$decrypted = "";
		$data = self::urlsafe_b64decode($data);
		openssl_private_decrypt($data,$decrypted,$pi_key);//私钥解密
		return $decrypted;
	}
780699
public function encrypt($data){
        $maxlength = $this->getMaxEncryptBlockSize($this->publicKey);
        $output='';
        while(strlen($data)){
            $input = substr($data, 0, $maxlength);
            $data = substr($data, $maxlength);
            openssl_public_encrypt($input, $encrypted, $this->publicKey);
            $output .= $encrypted;
        }
        $encryptedData =  base64_encode($output);
        return $encryptedData;
    }
1133767
public static String RSAKeyToString (PrivateKey key)
    {
        try {
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKeySpec spec = kf.getKeySpec(key, RSAPrivateKeySpec.class);
            StringBuilder buf = new StringBuilder();
            buf.append(spec.getModulus().toString(16))
                .append(SPLIT)
                .append(spec.getPrivateExponent().toString(16));
            return buf.toString();
        } catch (GeneralSecurityException gse) {
            log.warning("Failed to convert key to string", gse);
        }
        return null;
    }
881548
public function verifySign($para_temp, $secretKey = '', $privateKey = '', $publicKey = '') {
        $prestr = $para_temp;
        if(is_array($para_temp)) {
            //除去待签名参数数组中的空值和签名参数
            $para_filter = $this->paraFilter($para_temp);
            //对待签名参数数组排序
            $para_sort = $this->argSort($para_filter);
            //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
            $prestr = $this->createLinkstring($para_sort);
        }
        
        $isSgin = false;
        switch (strtoupper(trim($para_temp['sign_type']))) {
            case "MD5" :
                $ApiMd5Sign = new ApiMd5Sign();
                $ApiMd5Sign = $ApiMd5Sign->setSecretKey($secretKey);
                $ApiMd5Sign = $ApiMd5Sign->setPrivateKey($privateKey);
                $isSgin = $ApiMd5Sign->verifySign($prestr, $para_temp['sign']);
                break;
            case "RSA2" :
                $ApiRsaSign = new ApiRsaSign();
                $ApiRsaSign = $ApiRsaSign->setPrivateKey($privateKey);
                $ApiRsaSign = $ApiRsaSign->setPublicKey($publicKey);
                $isSgin = $ApiRsaSign->verifySign($prestr, $para_temp['sign']);
                break;
            default :
                $isSgin = false;
        }
        return $isSgin;
    }
578095
public static function implode_pk($data)
	{
		if (count(static::$_primary_key) == 1)
		{
			$p = reset(static::$_primary_key);
			return (is_object($data)
				? strval($data->{$p})
				: (isset($data[$p])
					? strval($data[$p])
					: null));
		}

		$pk = '';
		foreach (static::$_primary_key as $p)
		{
			if (is_null((is_object($data) ? $data->{$p} : (isset($data[$p]) ? $data[$p] : null))))
			{
				return null;
			}
			$pk .= '['.(is_object($data) ? $data->{$p} : $data[$p]).']';
		}

		return $pk;
	}
489058
def sign_raw_data(raw_data, privatekey_hex):
    
    if not isinstance(raw_data, (str, unicode)):
        raise ValueError("Data is not a string")

    raw_data = str(raw_data)

    si = ECSigner(privatekey_hex)
    si.update(raw_data)
    return si.finalize()
977952
protected function generateXml(Connect $connect, $privateKey, $data)
    {
        $certificateGen = (new X509CertificateGen())->createX509Certificate($privateKey);

        $certificate = new X509Certificate();
        $certificate->loadPem($certificateGen);

        $builder = new MetadataBuilder();
        $xml = $builder->build($data['entityID'], $data['acs'], $data['logout'], $certificate);

        $path = $connect->getConfig()->getSamlMetadataBaseDir().'/'.$connect->getConfig()->getSpMetadataFile();
        file_put_contents($path, $xml);

        $message = (new SpEntityConfigurationMessage())
            ->setXml($xml);

        $message = (new SignedMessageDecorator($message))
            ->setCertificate((new X509CertificateGen())->createX509Certificate($privateKey))
            ->sign($privateKey);

        $certificate = $connect->getSaml()
            ->getMetadata()
            ->getFirstIdpSsoDescriptor()
            ->getFirstKeyDescriptor(KeyDescriptor::USE_ENCRYPTION)
            ->getCertificate()
            ->toPem();

        return (new MessageResponse($message))->buildEncrypted($certificate);
    }
348317
function _rsapem_privateKeyToPkcs1HexString(rsaKey) {
    var result = _rsapem_derEncodeNumber(0);
    result += _rsapem_derEncodeNumber(rsaKey.n);
    result += _rsapem_derEncodeNumber(rsaKey.e);
    result += _rsapem_derEncodeNumber(rsaKey.d);
    result += _rsapem_derEncodeNumber(rsaKey.p);
    result += _rsapem_derEncodeNumber(rsaKey.q);
    result += _rsapem_derEncodeNumber(rsaKey.dmp1);
    result += _rsapem_derEncodeNumber(rsaKey.dmq1);
    result += _rsapem_derEncodeNumber(rsaKey.coeff);

    var fullLen = _rsapem_encodeLength(result.length / 2);
    return '30' + fullLen + result;
}