KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacSHA256");
keyGenerator.init(192); //48位id标识应用
SecretKey originalKey = keyGenerator.generateKey();
Mac mac = Mac.getInstance("hmacsha256");
SecretKeySpec spec = new SecretKeySpec("apiSecret".getBytes(), "hmacsha256");
mac.init(spec);
byte[] hexDigits = mac.doFinal("".getBytes());
验签和产生签名使用的是同一个key.
//generateKey
KeyPairGenerator myKeyGen= KeyPairGenerator.getInstance("RSA");
myKeyGen.initialize(1024);
KeyPair myKeyPair = myKeyGen.generateKeyPair();
//sign
byte[] info = content.getBytes("utf-8");
Signature mySig = Signature.getInstance("SHA1WithRSA");
mySig.initSign(privateKey); //用私钥初始化签名对象
mySig.update(info);
byte[] sigResult = mySig.sign();
String result = Base64.getEncoder().encodeToString(sigResult);
//verify
Signature mySig = Signature.getInstance("SHA1WithRSA");
byte[] info = content.getBytes();
mySig.initVerify(publicKey);
mySig.update(info);
byte[] sign = Base64.getDecoder().decode(signInBase64);
boolean verify = mySig.verify(sign); //得到验证结果
产生签名使用的私钥,验签使用的公钥。
Posted in: java基础
Comments are closed.