|
|
@@ -1,6 +1,45 @@
|
|
|
package com.malk.lianan;
|
|
|
|
|
|
+import cn.hutool.core.codec.Base64;
|
|
|
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
|
|
+
|
|
|
+import java.security.KeyFactory;
|
|
|
+import java.security.PrivateKey;
|
|
|
+import java.security.Signature;
|
|
|
+import java.security.spec.PKCS8EncodedKeySpec;
|
|
|
+
|
|
|
public class RsaUtil {
|
|
|
|
|
|
+ private final static String KEY_RSA = "RSA";
|
|
|
+ private final static String KEY_RSA_SIGNATURE = "SHA256WithRSA";
|
|
|
+ private static BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
|
|
|
+
|
|
|
+ public static String sign(byte[] data, String privateKey) {
|
|
|
+ String str = "";
|
|
|
+ try {
|
|
|
+// 解密由 base64 编码的私钥
|
|
|
+ byte[] bytes = decryptBase64(privateKey);
|
|
|
+// 构造 PKCS8EncodedKeySpec 对象
|
|
|
+ PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(bytes);
|
|
|
+// 指定的加密算法
|
|
|
+ KeyFactory factory = KeyFactory.getInstance(KEY_RSA,bouncyCastleProvider);
|
|
|
+// 取私钥对象
|
|
|
+ PrivateKey key = factory.generatePrivate(pkcs);
|
|
|
+// 用私钥对信息生成数字签名
|
|
|
+ Signature signature =Signature.getInstance(KEY_RSA_SIGNATURE,bouncyCastleProvider);
|
|
|
+ signature.initSign(key);
|
|
|
+ signature.update(data);
|
|
|
+ str = encryptBase64(signature.sign());
|
|
|
+ } catch (Exception e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ return str;
|
|
|
+ }
|
|
|
+ public static byte[] decryptBase64(String key) throws Exception {
|
|
|
+ return Base64.decode(key);
|
|
|
+ }
|
|
|
+ public static String encryptBase64(byte[] key) throws Exception {
|
|
|
+ return new String(Base64.encode(key));
|
|
|
+ }
|
|
|
|
|
|
}
|