加密将代码从Node JS转换为Java

时间:2019-05-17 10:51:49

标签: java cryptography rsa licensing signature

我要在离线模式下检查登录: 我在节点js上找到了以下代码

const crypto = require('crypto')
const {
  KEYGEN_PUBLIC_KEY,
  LICENSE_KEY
} = process.env

// Extract key and signature from the license key payload
const [encodedKey, encodedSignature] = LICENSE_KEY.split('.')

// Decode the base64 encoded key
const key = Buffer.from(encodedKey, 'base64').toString()

// Verify the signature
const verifier = crypto.createVerify('sha256')
verifier.write(key)
verifier.end()

const ok = verifier.verify(KEYGEN_PUBLIC_KEY, encodedSignature, 'base64')

之后,我尝试在Java上重写此代码

byte[] publicBytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);

Signature sign = Signature.getInstance("SHA256withRSA");
sign.initVerify(pubKey);
byte[] decode = Base64.getDecoder().decode(signature.getBytes(StandardCharsets.UTF_8));
System.out.println(sign.verify(decode));

但这不起作用。 Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character 2d是例外 有人可以帮我解决这个错误吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试以下代码吗?

byte[] publicBytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);

MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(publicBytes);
byte[] outputDigest = messageDigest.digest();

此后,您可以使用常规的Base64解码功能。 您可以在下面的示例中参考。 https://www.quickprogrammingtips.com/java/how-to-create-sha256-rsa-signature-using-java.html