The WebCrypto assurances don't appear to be triggering

Looking at my code:

var keyData = `-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----`;

var ciphertext = '...';

// based on the reference from https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#PKCS_8_import
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;
}

keyData = keyData
    .replace(/-+[^-]+-+/g, '')
    .replace("\n", '')
    .replace("\r", '');
keyData = str2ab(window.atob(keyData));

window.crypto.subtle.importKey(
   'pkcs8',
    keyData,
    {name: 'RSA-OAEP'},
    true,
    'decrypt'
).then(function(privateKey) {
alert('this far');
    window.crypto.subtle.decrypt(
    {
      name: "RSA-OAEP"
    },
    privateKey,
    ciphertext
  ).then(function(plaintext) {
      alert(plaintext);
  })
});

See it live on JSFiddle (including complete private key and ciphertext):

https://jsfiddle.net/akcq65o7/1/

In line with the documentation, window.crypto.subtle.importKey utilizes a Promise, hence the need for then(). However, the line alert('this far'); doesn't seem to be executing. No errors are appearing in the JS console either.

Any suggestions?

Answer №1

Upon reviewing the script, I've identified a few minor issues that are highlighted in the code snippet below:

var keyData = `-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQD+80tGPsmRlVBe
+BHRwrBtqKRMzkYBfgmiP6EINNN8NDdXY80KNMb8w+Rx97GgFGPrqVuIPy6RnNRz
Qd77oXmlSqwOPuGIl+x/fga9hL7Z7CfvZz1pqSwBT01OtLNbTMJEMiZtImqOiLIr
1PE8kOVF3B2VssZhwjVy8qppYmix/5XiZM/1nOUvMeiHCq0UAJ4lNA2fLVQkQZSU
pG2HdNIuDHfBBhEGvKdXK4oRwOgeAadpUbOwhUcTU9SSUi4Gvkg6S3WVFdm4seXN
kV2mav9j/oGUF22YO60/y5GDLBEbfsIOpGVLjFnqUJbOu9wBiz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O665IsV6NqzXnJLfhwgkztMDt8XawKBgBFqDwEqr9/46iPP7I4D
OTzDCLLKnwx/2X6OtWKNC3h6mCCCp74tYtkpJlXxmD2XIm1W/onvHGvwrZBU8Gp2
eUBF7ioXhH2HUKBPV6X9y3f70jOoD9iDl4ukXbXMFNI8LPzzEBCgJi0VfRPYJuqG
XWYyiGL0bGW4mhUd5/ZFkbWg
-----END PRIVATE KEY-----`;

var ciphertext = 'Sv99/pCslCtU+yAxV0dR+JyQ7yfiVF7+MCHErQEMSL7CyEndKikU7Al0IiRDx6Bd/PmKR6j0mU7WXISptZA1uE82jdDEAhcs9mQtdX18Or4OceIGcqHcHDCZWFQygHI0VMbywVv5C18ydFDuGvHL/dga9ji8IbFW393sEfjx6JtV8Nl4+yiEbee/+dBSQTg+E98asW1Tg59HUNc/fE1r7Muw6hgl7eiF/GxndYg7O957LNH4T3Vi6qutG4mP0frGJ3za6RNkuRrO5Wud3WnDOndHNAoLW7cuMyvzXzfhh3YMPqmkKtRsChJkV+DfPU8HdALfuyP/botQnUGCmwanKg==';

// from https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#PKCS_8_import
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;
}

keyData = keyData
    .replace(/-+[^-]+-+/g, '')
    .replace("\n", '')
    .replace("\r", '');
keyData = str2ab(window.atob(keyData));

window.crypto.subtle.importKey(
    'pkcs8',
    keyData,
    {
        name: 'RSA-OAEP', 
        hash: "SHA-256"                                     // Modification 1: Set digest
    },                                                      
    true,
    ['decrypt']                                             // Modification 2: Use brackets [...]
).then(function(privateKey) {
    console.log('this far');
    window.crypto.subtle.decrypt(
        {
            name: "RSA-OAEP"
        },
        privateKey,
        str2ab(window.atob(ciphertext))                     // Modification 3: Base64 decode ciphertext and load into ArrayBuffer
    ).then(function(plaintext) {
        console.log(new TextDecoder().decode(plaintext));   // Modification 4: UTF-8 decode plaintext
    })
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with jQuery not detecting click events

Here is an example of HTML: <div class="sortable-buttons"> <ul> <li><a>Recent</a></li> <li><a>Popular</a></li> <li><a>Being Discussed</a></li> </ul> </div ...

Retrieving the title value of the parent span element through a child node with the help of JavaScript or

Rebuilding the query. The HTML element structure is as follows: <li class="inner"><span class="plus" id="sidehome" title="siteHome">SiteHome</span> <ul style="display:none"> <li class="inner"> <span class="plus" id=" ...

obtaining attribute values from chosen items in a multiselect dropdown menu

I am using jQuery to create a multi-select element. For instance, consider the following example: <select multiple id="multiple"> <option value="1" type="Alice">Option 1</option> <option value="2" type="Bob">Option 2</o ...

Steps to displaying the result

new Vue({ data: { folders : [{ name : 'folder1', isActive : 1, }, { name : 'folder2', isActive : 0, }, ] } } }) Is there a way to access the active val ...

Looking to display a single Angular component with varying data? I have a component in Angular that dynamically renders content based on the specific URL path

I have a component that dynamically renders data based on the URL '/lp/:pageId'. The :pageId parameter is used to fetch data from the server in the ngOnInit() lifecycle hook. ngOnInit(){ this.apiHelper.getData(this.route.snapshot.params.pageId) ...

Chrome has recently updated to version 92, causing unexpected exceptions even when the driver is said to be compatible

After updating the Chrome driver to version 92.0.4515.107 and installing the .rpm file for Chrome version 92, I encountered an exception when running the code: selenium.common.exceptions.SessionNotCreatedException: Message: session not created: No matching ...

I am facing an issue where my Popover functions correctly when elements are added using HTML, but not when they are dynamically created

I'm currently working on a method to incorporate multiple popovers that have a similar appearance to the following: The screenshot of my first JsFiddle project (click to view) The initial progress I've made can be seen in my first JsFiddle, acc ...

Managing media file transfers using multer and mongodb in a Node.js environment

As I work on developing a blog-style application for a business website, I have successfully implemented a login system and a basic blog structure. My current focus is on enabling users to upload images along with their blog posts. At the moment, I am trou ...

Warning: React Element creation caution with flow-router integration

Whenever I incorporate the following code into my Meteor app: Home = FlowRouter.route("/", { name: "App", action(params) { ReactLayout.render(App); } }); An error message pops up in the Chrome console: Warning: React.createElement: type shoul ...

Using the React context without explicitly setting the contextType or defining a default context

Is it possible to access the closest context from a provider without having to explicitly define contextType in a component by using this.context? Alternatively, is there a way to establish a default context so that when I use this.context, I automaticall ...

How can you match the width of a series of elements to the width of an image directly preceding the div?

Looking to ensure that a series of captions have the same width as the images preceding them. This is the HTML code: <div class="theparent"> <img src="pic.jpg"/> <div class="caption"> hello </div> <div> <div ...

Invoking a React function repeatedly (every second)

Currently, I am working with React and utilizing Material UI to create a modal. The modal is rendered as part of the body of the code, placed at the bottom of the page. Its visibility is controlled by the state; if it's open or closed. However, I&apos ...

Contrasting loading data from an empty state and having no items present

On my web page, I pull items from an API and display them. The API request is made in the created hook. I need to display a [loading] message while waiting for the API response, and a [no items] message if the loading is complete but there are no items ava ...

Best practices for building an Ember frontend and Node backend application

I'm currently working on a project that involves an ember frontend and a node backend. Within my ember-cli app, I've configured the .ember-cli file to proxy requests to node like this: { "proxy": "http://localhost:3000" } I've had to es ...

How can we fetch data from the server in Vue 2.0 before the component is actually mounted?

Can anyone help me with this question noted in the title? How can I prevent a component from mounting in <router-view> until it receives data from the server, or how can I fetch the data before the component is mounted in <router-view>? Here a ...

Inserting an item into ng-model within a dropdown menu

I have a select box populated with data from my backend. This data is an array of objects: [Object { superkund_id="4", nod_id="12068", namn="Växjö Fagrabäck"}, Object { superkund_id="5", nod_id="9548", namn="Halmstad Bågen / Pilen"}] I am using ng-o ...

Hiding a div upon submission using jquery validator

I need assistance with a validator that currently hides the submit buttons and displays a "please wait" message after the user clicks submit. The issue is that it also triggers this behavior when a date field validates. Is there a way to modify the code s ...

Check out the Pa11y JSON configuration file specifically designed for actions by visiting the following link: https://github.com/pa11y/pa11

Our automated accessibility testing is conducted using the Jenkins CI tool with the help of pa11y. Below is the Jenkinsfile used to execute these tests: node('mypod') { container('centos') { def NODEJS_HOME env.NODEJS_HOME = "${t ...

When passing req.body to another file for processing, it is displaying as undefined in node.js

Currently tackling an issue with a project involving nodejs where the request body is showing up as undefined Fetching some data on the client side, but encountering difficulties Received an error pointing out that the property is either undefined or nul ...

Making a POST request to a Next.js API route results in a 500 Internal Server Error being sent back

Check out the code in createComment.ts file, which serves as a Next.js api route: import type { NextApiRequest, NextApiResponse } from 'next' import sanityClient from "@sanity/client" const config = { dataset: process.env.NEXT_PUBLI ...