RSAUtils { public static String sign(byte[] data, String privateKey) throws Exception { Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(decodePrivateKey(privateKey)); signature.update(data); return Base64Utils.encode(signature.sign()); }  static Pair<RSAPublicKey, RSAPrivateKey> genKeyPair(int rsaKeySize); static String encodeBase64(Key key); static PrivateKey decodePrivateKey(String key); static PublicKey decodePublicKey(String publicKey); static String sign(byte[] data, String privateKey); static boolean verify(byte[] data, String publicKey, String sign); static RSAPublicKey getPublicKey(String modulus, String exponent); static RSAPrivateKey getPrivateKey(String modulus, String exponent); static byte[] encryptByPublicKey(byte[] data, RSAPublicKey publicKey); static byte[] decryptByPrivateKey(byte[] data, RSAPrivateKey privateKey); static byte[] decryptByPrivateKey(byte[] data, String privateKey); static byte[] decryptByPublicKey(byte[] data, String publicKey); static byte[] encryptByPublicKey(byte[] data, String publicKey); static byte[] encryptByPrivateKey(byte[] data, String privateKey); static void main(String[] args); static final int RAS_KEY_SIZE; static final String KEY_ALGORITHM; static final String KEY_ALGORITHM_PADDING; static final String SIGNATURE_ALGORITHM; }
@Test public void testSign() throws Exception { String source = "这是一行测试RSA数字签名的无意义文字"; System.out.println("===========私钥加密——公钥解密======================="); System.out.println("原文字:\n" + source); byte[] data = source.getBytes(); byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey); System.out.println("加密后:\n" + new String(encodedData)); byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey); String target = new String(decodedData); System.out.println("解密后:\n" + target); System.out.println("============私钥签名——公钥验证签名==================="); String sign = RSAUtils.sign(encodedData, privateKey); System.out.println("签名:\n" + sign); boolean status = RSAUtils.verify(encodedData, publicKey, sign); System.out.println("验证结果:\n" + status); }