Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...