跳到主要内容

附录2

签名验证

第 1 步:导入所需的包

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;

第 2 步:从公钥字节创建一个PublicKey对象

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBytes));

第 3 步:Create a Signature object and initialize it with the public key

Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(publicKey);

第 4 步:将除 signedMessage 之外的所有参数转换为字节

response.setACQ("FNX");
response.setDeviceBrandModel("SB-001");
response.setDeviceID("SB000000001");
response.setLang("EN");
response.setTrxRefNo("FNX202302170100000000000000001");
response.setTrxCurr("MYR");
response.setTrxAmt("100.00");
response.setTrxDateTms("20230217121212236");
response.setTrxPymtBrand("PN");
response.setMID("000010000010440");
response.setTID("60003614");
Gson gson = new Gson();
String jsonStr = gson.toJson(response);
byte[] messageBytes = jsonStr.getBytes();

第 5 步:使用消息字节更新 Signature 对象

signature.update(messageBytes);

第 6 步: 将 signedMessage 转换为字节并验证它

boolean verified = signature.verify(signedMessageBytes);