私钥签名

@param data
@param privateKey
@return
@throws Exception
179577
public static String encryptByPrivateKey(String data, String privateKey) throws Exception {
		PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(base64.decode(privateKey));
		KeyFactory keyf = KeyFactory.getInstance("RSA");
		PrivateKey priKey = keyf.generatePrivate(priPKCS8);
		java.security.Signature signature = java.security.Signature.getInstance("SHA256WithRSA");

		signature.initSign(priKey);
		signature.update(data.getBytes("UTf-8"));
		byte[] signed = signature.sign();
		return base64.encodeToString(signed);
	}
118194
public static PrivateKey decryptPrivateKey(String privateKeyStr) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64Util.decode(privateKeyStr));
            return keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }
996313
public static boolean checkByPublicKey(String data, String sign, String publicKey) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		byte[] encodedKey = base64.decode(publicKey);
		PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
		java.security.Signature signature = java.security.Signature.getInstance("SHA256WithRSA");
		signature.initVerify(pubKey);
		signature.update(data.getBytes("utf-8"));
		return signature.verify(base64.decode(sign.getBytes("UTf-8")));
	}
1077500
private PrivateKey readEcPrivateKey(String fileName) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, NoSuchProviderException
    {
    	StringBuilder sb = new StringBuilder();
    	BufferedReader br = new BufferedReader(new FileReader(fileName));
    	try {
	    	char[] cbuf = new char[1024];
	    	for (int i=0; i <= 10*1024; i++) {
	    		if (!br.ready())
	    			break;
	    		int len = br.read(cbuf, i*1024, 1024);
	    		sb.append(cbuf, 0, len);
	    	}
	    	if (br.ready()) {
	    		throw new IndexOutOfBoundsException("JWK file larger than 10MB");
	    	}
	    	Type mapType = new TypeToken<Map<String, String>>(){}.getType();
	    	Map<String, String> son = new Gson().fromJson(sb.toString(), mapType);
	    	try {
				@SuppressWarnings({ "unchecked", "rawtypes" })
				EllipticCurveJsonWebKey jwk = new EllipticCurveJsonWebKey((Map<String, Object>)(Map)son);
				Base64Encoder enc = new Base64Encoder();
				ByteArrayOutputStream os = new ByteArrayOutputStream();
	        	enc.encode(jwk.getPrivateKey().getEncoded(), 0, jwk.getPrivateKey().getEncoded().length, os);
				return jwk.getPrivateKey();
			} catch (JoseException e1) {
				e1.printStackTrace();
			}
	        return null;
    	} finally {
    		br.close();
    	}
    }
677803
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
        String keyBytes = Base64Utils.encode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes.getBytes());
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicK);
        signature.update(data);
        return signature.verify(Base64Utils.decode(sign).getBytes());
    }
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()
1112110
public static PrivateKey readPrivateKey(String pemResName) throws Exception {
        InputStream contentIS = TokenUtils.class.getResourceAsStream(pemResName);
        byte[] tmp = new byte[4096];
        int length = contentIS.read(tmp);
        PrivateKey privateKey = decodePrivateKey(new String(tmp, 0, length));
        return privateKey;
    }
1186102
public static byte[] initKey() throws Exception{
		//密钥生成器
		KeyGenerator keyGen = KeyGenerator.getInstance("AES");
		//初始化密钥生成器
		keyGen.init(128);  //默认128，获得无政策权限后可用192或256
		//生成密钥
		SecretKey secretKey = keyGen.generateKey();
		return secretKey.getEncoded();
	}
793990
public static byte[] sign(byte[] text, PrivateKey key, String algorithm) throws SignatureException {
        Signature signature;
        try {
            signature = Signature.getInstance(algorithm);
            signature.initSign(key);
        } catch (GeneralSecurityException e) {
            throw new IllegalArgumentException("cannot initialize signature for algorithm " + algorithm, e);
        }
        signature.update(text);
        return signature.sign();
    }
963505
public static String rsaSign(String content, String privateKey) {

        if (null == content || privateKey == null) {
            return null;
        }

        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey, Base64.DEFAULT));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(content.getBytes(CHARSET));
            byte[] signed = signature.sign();
            return Base64.encodeToString(signed, Base64.DEFAULT);
        } catch (Exception e) {
            //  这里是安全算法，为避免出现异常时泄露加密信息，这里不打印具体日志
            HMSAgentLog.e("rsaSign error");
        }

        return null;
    }
211413
def get_privatekey(keydata):
    """"""
    key = serialization.load_pem_private_key(
        keydata,
        password=None,
        backend=default_backend(),
    )
    return key
4364
@Override
    public String getName(String key) throws Exception {
        IPortletDefinitionRegistry registry =
                PortletDefinitionRegistryLocator.getPortletDefinitionRegistry();

        IPortletDefinition portletDefinition;
        if (StringUtils.isNumeric(key)) {
            portletDefinition = registry.getPortletDefinition(key);
        } else {
            portletDefinition = registry.getPortletDefinition(key.split("\\.")[1]);
        }
        return portletDefinition.getName();
    }
695779
public static String decryptData(String base64Data, String key) throws Exception {
		Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(HashKit.md5(key).toLowerCase().getBytes(), ALGORITHM));
		return new String(cipher.doFinal(Base64Kit.decode(base64Data)));
	}
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;
    }
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;
    }
846583
protected static final byte[] signISO9796(byte[][] key, byte[] data, int off, int len) throws Exception {
        CachingKey ck = new CachingKey(key, data, off, len);
        CachingKey result = cryptoKeysMap.get(ck);

        if (result != null) {
            result.successfulUses += 1;
            result.reused = true;
            return result.result;
        } else {
            if (cryptoKeysMap.size() > MAX_CACHE) {
                try {
                    CachingKey[] keys = cryptoKeysMap.keySet().toArray(new CachingKey[cryptoKeysMap.size()]);
                    Arrays.sort(keys, cachingKeyComparator);
                    if (cachingKeyComparator.compare(keys[0], keys[keys.length - 1]) < 0) {
                        for (int i = 0; i < cryptoKeysMap.size() / 5; i++) {
                            cryptoKeysMap.remove(keys[i]);
                            keys[i + 1 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[i + 2 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[i + 3 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[i + 4 * cryptoKeysMap.size() / 5].successfulUses--;
                        }
                    } else {
                        for (int i = 0; i < cryptoKeysMap.size() / 5; i++) {
                            cryptoKeysMap.remove(keys[keys.length - 1 - i]);
                            keys[keys.length - 1 - i - 1 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[keys.length - 1 - i - 2 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[keys.length - 1 - i - 3 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[keys.length - 1 - i - 4 * cryptoKeysMap.size() / 5].successfulUses--;
                        }
                    }
                } catch (Exception e) {
                    // do nothing. since this code is used for the command line utility, no log is taken.
                }
                 
            }
        }

        /** Invoked by LTPADigSignature **/
        BigInteger n = new BigInteger(key[0]);
        BigInteger e = new BigInteger(key[2]);
        BigInteger p = new BigInteger(key[3]);
        BigInteger q = new BigInteger(key[4]);
        BigInteger d = e.modInverse((p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)));
        KeyFactory kFact = null;
        if (LTPAKeyUtil.isIBMJCEAvailable()) {
            kFact = KeyFactory.getInstance(CRYPTO_ALGORITHM, IBMJCE_NAME);
        } else {
            kFact = KeyFactory.getInstance(CRYPTO_ALGORITHM);
        }


        BigInteger pep = new BigInteger(key[5]);
        BigInteger peq = new BigInteger(key[6]);
        BigInteger crtC = new BigInteger(key[7]);
        RSAPrivateCrtKeySpec privCrtKeySpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, pep, peq, crtC);
        PrivateKey privKey = kFact.generatePrivate(privCrtKeySpec);

        Signature rsaSig = null;
        if (LTPAKeyUtil.isIBMJCEAvailable()) {
            rsaSig = Signature.getInstance(SIGNATURE_ALGORITHM, IBMJCE_NAME);
        } else {
            rsaSig = Signature.getInstance(SIGNATURE_ALGORITHM);
        }
        rsaSig.initSign(privKey);
        rsaSig.update(data, off, len);
        byte[] sig = rsaSig.sign();

        cryptoKeysMap.put(ck, ck);
        ck.result = sig;
        ck.successfulUses = 0;

        return sig;
    }
1268970
public function sign($data)
    {
        if (!ctype_xdigit($this->hex)) {
            throw new \Exception('The private key must be in hex format.');
        }

        if (empty($data)) {
            throw new \Exception('You did not provide any data to sign.');
        }

        $e = Util::decodeHex(hash('sha256', $data));

        do {
            if (substr(strtolower($this->hex), 0, 2) != '0x') {
                $d = '0x'.$this->hex;
            } else {
                $d = $this->hex;
            }

            $k = SecureRandom::generateRandom(32);

            $k_hex = '0x'.strtolower(bin2hex($k));
            $n_hex = '0x'.Secp256k1::N;


            $Gx = '0x'.substr(Secp256k1::G, 2, 64);
            $Gy = '0x'.substr(Secp256k1::G, 66, 64);

            $P = new Point($Gx, $Gy);

            // Calculate a new curve point from Q=k*G (x1,y1)
            $R = Util::doubleAndAdd($k_hex, $P);

            $Rx_hex = Util::encodeHex($R->getX());

            $Rx_hex = str_pad($Rx_hex, 64, '0', STR_PAD_LEFT);

            // r = x1 mod n
            $r = Math::mod('0x'.$Rx_hex, $n_hex);

            // s = k^-1 * (e+d*r) mod n
            $edr  = Math::add($e, Math::mul($d, $r));
            $invk = Math::invertm($k_hex, $n_hex);
            $kedr = Math::mul($invk, $edr);

            $s = Math::mod($kedr, $n_hex);

            // The signature is the pair (r,s)
            $signature = array(
                'r' => Util::encodeHex($r),
                's' => Util::encodeHex($s),
            );

            $signature['r'] = str_pad($signature['r'], 64, '0', STR_PAD_LEFT);
            $signature['s'] = str_pad($signature['s'], 64, '0', STR_PAD_LEFT);
        } while (Math::cmp($r, '0') <= 0 || Math::cmp($s, '0') <= 0);

        $sig = array(
            'sig_rs'  => $signature,
            'sig_hex' => self::serializeSig($signature['r'], $signature['s']),
        );

        return $sig['sig_hex']['seq'];
    }