Java RSA (SHA1withRSA)簽名和驗籤

FrankYou發表於2018-03-12
static {
    try {
        SIGNATURE = Signature.getInstance("SHA1withRSA", "BC");
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | NoSuchProviderException e) {
        throw Throwables.propagate(e);
    }
}

public static String getSignature(Map<String, String> map, String pfxPath, String pfxPasswd) {
    try {
        SIGNATURE.initSign(X509Certs.getPrivateKey(pfxPath, pfxPasswd).getPrivateKey());
        SIGNATURE.update(DigestUtils.sha1Hex(buildReqParams(map, false)).getBytes(Charsets.UTF_8));
        return Base64.encodeBase64String(SIGNATURE.sign()).replaceAll("\r|\n", "");
    } catch (Throwable e) {
        throw Throwables.propagate(e);
    }
}

public static void verifySign(Map<String, String> map, String certPath) throws GatewayFrontException {
    try {
        byte[] sign = Base64.decodeBase64(map.get("signature").getBytes(Charsets.UTF_8));
        map.remove("signature");
        SIGNATURE.initVerify(X509Certs.getVerifyPublicKey(certPath));
        SIGNATURE.update(DigestUtils.sha1Hex(ExPayUtil.buildReqParams(map, false)).getBytes(Charsets.UTF_8));
        Preconditions.checkState(SIGNATURE.verify(sign), ExPayConstant.VERIFY_SIGNATURE_FAILUE);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

 

相關文章