如何在Runscope测试中使用私钥对请求进行签名?
I've tackled this exact issue before—CryptoJS alone won't cut it for RSA-based signing because it doesn't support asymmetric cryptography operations out of the box. Let's break down why your attempts weren't working and how to fix it.
Why Your Previous Code Failed
- Undefined error with
CryptoJS.SHA256withRSA: This method doesn't exist in CryptoJS. CryptoJS only handles hash functions (like SHA256) and symmetric encryption, not RSA signing/verification. - Short signature from plain SHA256: When you ran just
sha256(signingMetadata), you were only generating a SHA256 hash (32 bytes, ~44 characters in Base64) instead of performing an RSA signature with your private key. RSA signatures match the length of your key (e.g., 256 bytes for a 2048-bit key, ~344 characters in Base64), which is why your result looked off.
Working Solution Using jsrsasign
Runscope allows you to use libraries like jsrsasign (the same underlying library as the Postman Crypto library you used) to handle RSA signatures. Here's how to set it up:
Add jsrsasign to Runscope Globals
- Grab the minified version of jsrsasign and paste it into a Runscope global variable named
jsrsasign_code.
- Grab the minified version of jsrsasign and paste it into a Runscope global variable named
Write the Signature Function
Use this code in your Runscope pre-request or test script—it mirrors the logic from your Postman implementation:function encryptSignature(signingMetadata) { // Load the jsrsasign library from your global variable eval(globals.get('jsrsasign_code')); // Initialize the signature object with SHA256withRSA algorithm const sig = new KJUR.crypto.Signature({ alg: 'SHA256withRSA' }); // Initialize with your private key (store this in a Runscope secret/global variable) sig.init(globals.get('private_key')); // Update the signature with your metadata string sig.updateString(signingMetadata); // Generate the hexadecimal signature const hexSignature = sig.sign(); // Convert hex to Base64 (matches your Postman logic) const signedEncoded = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(hexSignature)); return signedEncoded; }Key Format Tips
- Make sure your private key is in PEM format (starts with
-----BEGIN PRIVATE KEY-----and ends with-----END PRIVATE KEY-----). jsrsasign supports both PKCS#1 and PKCS#8 formats, but double-check for any extra whitespace or line breaks that might cause issues. - Store your private key in a Runscope secret variable instead of a regular global to keep it secure.
- Make sure your private key is in PEM format (starts with
Verify the Result
Test the function by comparing its output to the signature generated by your Postman script. If they match, you're good to go—send the request to your verification service and confirm it passes.
内容的提问来源于stack exchange,提问作者Asia

