RSACoder extends Coder { public static String sign(byte[] data, String privateKey) throws Exception { byte[] keyBytes = decryptBASE64(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(priKey); signature.update(data); return encryptBASE64(signature.sign()); }  static String sign(byte[] data, String privateKey); static boolean verify(byte[] data, String publicKey, String sign); static byte[] decryptByPrivateKey(byte[] data, String key); static byte[] decryptByPublicKey(byte[] data, String key); static byte[] encryptByPublicKey(byte[] data, String key); static byte[] encryptByPrivateKey(byte[] data, String key); static String getPrivateKey(Map<String, Object> keyMap); static String getPublicKey(Map<String, Object> keyMap); static Map<String, Object> initKey(); static final String KEY_ALGORITHM; static final String SIGNATURE_ALGORITHM; }
@Test public void testSign() throws Exception { System.out.println("私钥加密——公钥解密"); String inputStr = "sign"; byte[] data = inputStr.getBytes(); byte[] encodedData = RSACoder.encryptByPrivateKey(data, privateKey); byte[] decodedData = RSACoder.decryptByPublicKey(encodedData, publicKey); String outputStr = new String(decodedData); System.out.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr); assertEquals(inputStr, outputStr); System.out.println("私钥签名——公钥验证签名"); String sign = RSACoder.sign(encodedData, privateKey); System.out.println("签名:" + sign); boolean status = RSACoder.verify(encodedData, publicKey, sign); System.out.println("状态:" + status); assertTrue(status); }