We have a server which is using RSA-OAEP to receive data from client.
I don't have access to server and the only way to check my result is to send a request and check its reply.
I've been able to send correct request with WebCrypto but I didn't have any success with php.
the code I'm using for JS :
var DataToEncrypt = 'abcd';
var pemEncodedKey = `-----BEGIN PUBLIC KEY-----
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-----END PUBLIC KEY-----`;
let encryptionKey;
function str2ab(str) {
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function importPublicKey(pem) {
const pemHeader = "-----BEGIN PUBLIC KEY-----";
const pemFooter = "-----END PUBLIC KEY-----";
const pemContents = pem.substring(pemHeader.length, pem.length - pemFooter.length);
const binaryDerString = window.atob(pemContents);
const binaryDer = str2ab(binaryDerString);
return window.crypto.subtle.importKey(
"spki",
binaryDer,
{
name: "RSA-OAEP",
hash: "SHA-256"
},
true,
["encrypt"]
);
}
function getMessageEncoding() {
const enc = new TextEncoder();
return enc.encode(DataToEncrypt);
}
async function encryptMessage() {
const encoded = getMessageEncoding();
const ciphertext = await window.crypto.subtle.encrypt(
{
name: "RSA-OAEP"
},
encryptionKey,
encoded
);
var decoder = new TextDecoder('utf8');
var b64encoded = btoa(String.fromCharCode.apply(null, new Uint8Array(ciphertext)));
document.getElementById('crypt').value = b64encoded;
}
document.getElementById('import').addEventListener("click", async () => {
encryptionKey = await importPublicKey(pemEncodedKey);
});
document.getElementById('encrypt').addEventListener("click", function(){
encryptMessage();
});
and this is my php function (using phpseclib) :
function encrypt($data) {
$key = '-----BEGIN PUBLIC KEY-----
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-----END PUBLIC KEY-----';
$rsa = new Crypt_RSA();
$rsa->setHash('sha256');
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->loadKey($key); // public key
$crypted = $rsa->encrypt($data);
return base64_encode($crypted);
}
echo encrypt('abcd');
I tried both of these methods result to send a request to server and as I mentioned earlier only js code works and php output does not work as expected.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…