Search code examples
javascriptphprsaphpseclibwebcrypto-api

simulate WebCrypto RSA-OAEP encryption in PHP


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.


Solution

  • I tried to encrypt something with js and decrypt it with php (phpseclib) using a pair of public/private keys which I produced and it was successful.

    After that I tried to reformat my public key to 64 chars in each line (it was in a single line like the one in js) and used both setHash('sha256') and setMGFHash('sha256') and now my php function works.

    new php function :

    function encrypt($data)
    {
        $key = '-----BEGIN PUBLIC KEY-----
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXX
    -----END PUBLIC KEY-----';
    
        $rsa = new Crypt_RSA();
        $rsa->setHash('sha256');
        $rsa->setMGFHash('sha256');
        $lk = $rsa->loadKey($key); // public key
        $crypted = $rsa->encrypt($data);
        return base64_encode($crypted);
    }