如何使用RSA256算法生成JWT签名?

时间:2018-07-19 07:36:16

标签: java jwt rsa docusignapi signature

我有一个PrivateKey和一个PublicKey,并使用privateKey初始化SignaturepublicKey来验证Signature

KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 

// decode public key
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(pubKeyBytes);
RSAPublicKey pubKey = (RSAPublicKey) 
keyFactory.generatePublic(publicSpec);

//decode private key
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(prvKeyBytes);
RSAPrivateKey privKey = (RSAPrivateKey) 
keyFactory.generatePrivate(privSpec);

//header and body Base64 decoded value
String headerString = mapper.writeValueAsString(header);
String headerEncoded = 
Base64.getUrlEncoder().encodeToString(headerString.getBytes());
String payloadString = mapper.writeValueAsString(payload);
String payloadEncoded = 
Base64.getUrlEncoder().encodeToString(payloadString.getBytes());
String tempAccessToken = hearderEncoded+"."+payloadString;

Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(privKey);
sign.update(tempAccessToken.getBytes("UTF-8"));
byte[] signatureBytes = sign.sign();
sign.initVerify(pubKey);
sign.update(tempAccessToken.getBytes("UTF-8"));     

String jsonToken = Base64.getUrlEncoder().encodeToString(signatureBytes);
String JWTtoken = tempAccessToken + "." + jsonToken; 

最后我在下面得到了JWT令牌(虚拟值):

  

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI4MzliN2NhNC02MDE1LTQ0OWQtOGZiNi02jkyYzk1Ny1jYTNjLTQyMWQtOTk2zY2VkNTAzZGViNWYiLCJleHAiOjE1MzIwMDQwMTcsImF1ZCI6ImFjY291bnQtZC5kb2N1c2lnbi5jb20iLzY29wZSI6InNpZ25hdHVyZSBpbXBlcnNvbmF0aW9uIn0 = .YNZzR0HgPWFm4dXMMHn3czEDRukYUB0Hyw7YP_BGY2dniIMqpH4Ctz5EEHcHrNT_mGImcp026w-isYgv56TTugYnkcAs8HH0YXa1Ey0skdjVYoZHdeyPC8Ci9xeOQF9wf4VjrBboaRxWkVXfngOHHewpV42NcaXxwmGlresWukHVmmjbFokd1Cm5BJKVhVlsZWuftcJlC3XoO9REjaZX78YTY9S5bpXmsZBYr20wHsWJrkP9EWGf7WSGHVXGBJfCpvOTZDC8_4B12ToD_RKjk6n5s8-F7X54KY4kx6Gg7xnk55vDw ==

我无法使用此JWT令牌获得accessToken。我将得到响应:

  

“错误”:“ invalid_request”;

注意:我正在使用此JWT令牌来获取 DocuSign应用程序的访问令牌。

1 个答案:

答案 0 :(得分:-1)

/* Header */
$header = json_encode(['typ' => 'JWT', 'alg' => 'sha256']);

/* Payload */
$payload = json_encode(['logged_in_id' => 1, 'logged_in_name' => 'Test', 'logged_in_username' => 'test']);

// Encode Header to Base64Url String
$base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));

// Encode Payload to Base64Url String
$base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));

// Create Signature Hash
$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, SECRET, true);

// Encode Signature to Base64Url String
$base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

// Create JWT
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;

这是创建JWT的完整代码。在上面的SECRET中,您需要在任何地方定义将用于生成JWT的秘密密钥的常量。

此代码是生成JWT的核心代码,但是您也可以使用任何可以简化您的任务的库,因为您无需编写完整的代码,只需包含该库并调用函数并传递仅必需的参数。

您可以下载库here