kjur / jsrsasign

The 'jsrsasign' (RSA-Sign JavaScript Library) is an opensource free cryptography library supporting RSA/RSAPSS/ECDSA/DSA signing/validation, ASN.1, PKCS#1/5/8 private/public key, X.509 certificate, CRL, OCSP, CMS SignedData, TimeStamp, CAdES and JSON Web Signature/Token in pure JavaScript.
https://kjur.github.io/jsrsasign
Other
3.28k stars 645 forks source link

Hello, using jsrsasign to load an existing RSA key pair cannot perform encryption and decryption. Could you please show me. #625

Open xhc-code opened 3 months ago

xhc-code commented 3 months ago

jsrsasign The version is 10.9.0. The algorithm used for encryption and decryption is RSA/ECB/OAEPWithSHA-256AndMGF1Padding.

The key and data are both encoded using base64. Is it necessary to convert the data into hex and pass it to the decrypt method? The official script did not find any tutorial on encryption and decryption.

Below is a demo, but it doesn't work properly.


// 1.Import jsrsasign library
const { KEYUTIL, KJUR, hextob64u, b64utohex } =  require('jsrsasign');

// 2.Base64 decoding private key
const base64PrivateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDYtvxVQJfybCiQvomuIjVqU2HQj2AisJgLzKmlVWaS44pysfxCJ/8d4T24btVOA9FKesn05lzYhjRjFVJiLcJXiL0adL5reD2m8sStF1hghVV03FP3PtmSnmfFg1Dte3jKjfTQvDz57+KW2xJxESiBAlFD0Ly+vrQUzubsnVVXFqvd6DojDZjpe5O+++MkBa+OWdN9VWGvr4wHMMU+Tc187E7EF/1fh4j9uYTdNlYUbVYtciPjtYRHvJ04HUc5Lw7XGTx1rUxP9PPCUn/uLHb2NShoEuv35aYLEoohsTjVJ9EKcuMv6tKBe4pMTEfHzBApZt3vKWcYakWWQYPQg22tAgMBAAECggEALNzcqc1gZzgKwcQf/mNoiWVPh3xW23eRUkgBCo/+VwQxwgKkhRGAl6/sNgUDtU3HAtMegcs6hzxpFeXxExAD/lj5RMPMM7VFlg0FuAtwKTMQ+MsvuqxRIDAYrWO82hzIaa4vcxK00MzfLHmXfL6fku1m41IP8LDL2M7oMS104D0Yn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ateKey}\n-----END PRIVATE KEY-----`;

// 3. Base64 decoding encrypted data
const encryptedDataB64 = "yq62qSO3ljGgHwSBeTL/4ka50xk5SS6XHizRHux3owwj4ryi4OxNFvVqC1hrApULZJQs6a2ITb6my/FU24gKsrLHEUqMzdWYPl10h9IlNlYvgffMjJS1kdVjeyDKwuFbbxnnjwulnwhlubcwJvvqZUD+yxV0vHmGBJmcj4nG3Jy2c900DxsJXHPqcFxBImPE8v6yeep5MBu3rpHg6nwCvg2+dw3GWLjsDrd5a/D4fUUPDz65yIZ+RYHe3HMfMb8RBlIYrV74Dewty2MhadwcLn5eWaXVPNk8035JSYfyOiF48dYgO8LYta1TbHFQoNlRvODC15+HmOEv1O0pSRiZ4w==";
const encryptedHex = b64utohex(encryptedDataB64);

// 4. Import private key
const rsaKey = KEYUTIL.getKey(pemPrivateKey);

// 5. Decrypt data
const decryptedHex = KJUR.crypto.Cipher.decrypt(encryptedHex, rsaKey, "RSAOAEP");
const decryptedData = hextob64u(decryptedHex);

// 6.Output decrypted data
console.log("decryptedData", decryptedData);