How can I decrypt with my public key using JSEncrypt Or Store Private key on client browser using javascript

1.4k views Asked by At

Case 1 : I need to encrypt data with a private key from server and decrypt it with a public key in frontend. I am using JSEncrypt and it is encrypting my data, but when I try do decrypt it, it is returning false.

var publicKeyPair1 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCz1zqQHtHvKczHh58ePiRNgOyiHEx6lZDPlvwBTaHmkNlQyyJ06SIlMU1pmGKxILjT7n06nxG7LlFVUN5MkW/jwF39/+drkHM5B0kh+hPQygFjRq81yxvLwolt+Vq7h+CTU0Z1wkFABcTeQQldZkJlTpyx0c3+jq0o47wIFjq5fwIDAQAB";

    // Encrypt with the Public key ...
    var jsEncrypt = new JSEncrypt();
    jsEncrypt.setPublicKey(publicKeyPair1);
    var encrypted = jsEncrypt.encrypt('secretdata');
    console.log(encrypted);//working 
    
    
    //encrypted data from server using public key pair 2
    var encryptedData ="PQSFoO4758hSjQ4QmfMarrUZx3gaxEciZVewaP9nZ8mICITpko430osF/BJrbfX8cGxWgL0n/Z6gDS9b9UthcEssdunzcYy3Rp+w137ImwmFxPVrGrft9yZUhiUpNeBmSd/7FijRvW50Qm6VCLJjaQhwG74TIVDuLLlup8wzSso=";
    
    
    
    var decrypt2 = new JSEncrypt();
    decrypt.setPrivateKey(publicKeyPair1);
    var uncrypted2 = decrypt.decrypt(encryptedData);
    console.log(uncrypted2); // return false - not working

Can anyone help how to decrypt using public key ?

If this scenario not working i have another approch to use two diff pair of public key and private key

Case 2 : my sensitive data ll encrypt by public key on server and decrypt by private key on client But how to keep secure my private key on client browser?

//diff pair server to client
var privateKeyPair2 = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALw5B0EfG/2CJFhvtLEjTCdZvd+kkAJHShOr46/mtx/S6eWONb1+NmbqDZQ7Pa7P0L8p9MOFDiNcqtbxm2+GE2rZ3sy+xXuHNuctirniFrzDIMWwI/UpP1SgBjQsj74pkyGvg/ubv9ZJaS7JZc2v4BZdiWGT9TzfFITPXrVrIo7bAgMBAAECgYAQtZdZRqO7e6QyXahS2WlXTPY4Nmm6ag2/dVD/OqIjJxwwjtFigyPdOwX9lMzDChvj/JuIB/XbWcyozEYaPnLWsIs8pADytM8ROvyVnEl/I3cUqtg6fbiToV3SQT3QxHzD4HIsgJVWLd6C+RM3+c9PL8jQyQIHJzlciUbICYFpwQJBANxHxnI0qcAEug5L9LYx1pRAGdJ+PzF2kFXKrpTwoVcBBVhv6htXrcS7WOEbjBB7GkJA5MBbIwOaS7XSI1B1XQsCQQDavnxYHLZrgdEoJEFOFBgJ0Z328+LwhWKcAt1fS/MYjbHNtDEPrrPzF5PsavJ2gTCYmVZKBJPGKHqiP1WiOZdxAkBiBYJ2EZ8z9iaA9CXJ6XWN9NRIyar/LL5fnth/KHDzEV46k1p+nk6SC7gqO6LhNpZhwxTH0AZNtRxZpU/XntIvAkEAjWVSRTaSKF4q0DLXT9wnSbmIzYgK6wSdoFEtvZr/kaCODXTrvcJlKb7U7J6ZCkcqHYoIwCHDT/T8iII+HXXy0QJBAILdzDpOOX8vjoZml49o0Fq6ylcyA/E7laK1Dbm7VvnV2r0UBLKiVswC9bFq2oJ1g7opJOE8++Oj89d66tMptdI=";

    // Decrypt with the private key Pair 2...
    var decrypt = new JSEncrypt();
    decrypt.setPrivateKey(privateKeyPair2);
    var uncrypted = decrypt.decrypt(encryptedData);
    console.log(uncrypted);//working
0

There are 0 answers