How to load PublicKey RSA from bytes using JavaScript

2.8k views Asked by At

I'm consuming a service developed in Java in an AngularJS application. This service returns me the bytes of an RSA public key. I need to mount the key through the bytes in JavaScript. In summary I need to do in JavaScript what is being done in Java as below:

 public static PublicKey loadPublicKey(String stored){
    byte[] data = Base64.decode(stored);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
    KeyFactory fact = KeyFactory.getInstance("RSA");
    return fact.generatePublic(spec);
}

Can anybody help me?

1

There are 1 answers

0
pedrofb On

You can use standard javascript WebCryptographyApi to import the public key for encryption or verify a signature. You need to set the algorithm and allowed operations depending on the expected key usage.

Encryption

//Convert the public key in base 64 (DER encoded) to array buffer
var publicKeyAB = str2ab(atob(publicKeyB64)); 

//import key to encrypt with RSA-OAEP   
crypto.subtle.importKey(
     "spki",    
      publicKeyAB, 
      { name: "RSA-OAEP", hash: {name: "SHA-256"}}, 
      false,
      ["encrypt"])
.then(function(key){
    //do something with the key               
}).catch(function(err) {
    console.log(err );
}); 

Verify a signature

//Convert the public key in base 64 (DER encoded) to array buffer
var publicKeyAB = str2ab(atob(publicKeyB64)); 

//import the key to verify RSA signature with SHA 256
crypto.subtle.importKey(
     "spki",    
      publicKeyAB, 
      {name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256'  }}, 
      false,
      ["verify"])
.then(function(key){
    //do something with the key               
}).catch(function(err) {
    console.log(err );
}); 

Utility functions

function str2ab(str) {
  var arrBuff = new ArrayBuffer(str.length);
  var bytes = new Uint8Array(arrBuff);
  for (var iii = 0; iii < str.length; iii++) {
    bytes[iii] = str.charCodeAt(iii);
  }
  return bytes;
}

See more examples here