public static final String CHARSET_NAME = "utf-8";
/** * 簽名 * @param plaintext 明文 * @return * @throws Exception */ public static String sign(String plaintext) throws Exception{ KeyFactory factory = KeyFactory.getInstance("RSA"); byte[] privateKeyBytes = Base64.getDecoder().decode("你的密鑰"); Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); PrivateKey privateKey = factory.generatePrivate(pkcs8EncodedKeySpec); Signature sign = Signature.getInstance("SHA1withRSA"); sign.initSign(privateKey); sign.update(plaintext.getBytes(CHARSET_NAME)); byte[] signBytes = sign.sign(); return bytesToBase64(signBytes); }
/** * 驗籤 * @param plaintext 明文 * @param sign 簽名 * @return * @throws Exception */ public static boolean verifySign(String plaintext, String sign) throws Exception{ byte[] publicKeyBytes = Base64.getDecoder().decode(HFBPublicKey); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec("你的公鑰"); KeyFactory factory = KeyFactory.getInstance("RSA"); PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec); Signature verifySign = Signature.getInstance("SHA1withRSA"); verifySign.initVerify(publicKey); verifySign.update(plaintext.getBytes(CHARSET_NAME)); boolean signedSuccess = verifySign.verify(Base64.getDecoder().decode(sign)); return signedSuccess; }