3

I'm trying to encrypt a string in javascript (firefox) using SubtleCrypto. The problem with that is, that the encryption only works for short inputs. Once the string (testdata) is longer than 190 characters, it will fail with an OperationError. Why does SubtleCrypto behave like that and how can I resolve it?

Code:

function str2ab(str) {
  var encoder = new TextEncoder('utf-8');
  return encoder.encode(str);
}

function ab2str(buf) {
  var decoder = new TextDecoder('utf-8');
  return decoder.decode(buf);
}

var keypair;
var algorithmKeyGen = {
  name: 'RSA-OAEP',
  modulusLength: 2048,
  publicExponent: new Uint8Array([1,
    0,
    1
  ]), // Equivalent to 65537
  hash: {
    name: 'SHA-256'
  }
};
var crypter = window.crypto.subtle;

function encrypt(buffer) {
  return crypter.encrypt(algorithmKeyGen, keypair.publicKey, buffer).then(
    function(data) {
      alert(ab2str(data));
    },
    function(error) {
      alert(error);
    }
  );
}

var testdata = "aasasadasdaasasadasdaasazzzzzzzzzzzzzzzzzzzzuuuuuuuuuuuuuuuuuuuuuuuzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzuuuuudddsdfssssssssssdddddddddddzzzzzzzzzzzzzzzzzzzzzzzzzzzzzppppppggppppppppppppppppssssstt"

crypter.generateKey(algorithmKeyGen, true, [
  'sign',
  'encrypt',
  'decrypt',
  'verify',
  'deriveKey'
]).then(function(res) {
  keypair = res;
  encrypt(str2ab(testdata));
}, console.error.bind(console, 'Unable to generate a key'));
4

2 回答 2

4

RSA is not meant for bulk encryption. The specific amount of data that can be encrypted with RSA is dependent on the key size and the padding you are using.

A 2048 bit key allows for 256 bytes of which the OAEP padding takes 42 bytes, leaving around 214 bytes for encrypted data.

Usually you would use the RSA for encrypting a symmetric key that are then used for encrypting the actual data. Often referred to as hybrid encryption.

于 2016-04-21T14:50:14.467 回答
0

After some research, I found the following possible causes for your problem:

Browser specific:

  • Wrong Firefox version. The library is supported for v34, and there is a chance that compability levels depend on the version of the browser you use. Make sure you have the right versions:

https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt

When encrypting data:

  • Your counter member of normalizedAlgorithm does not have length 16 bytes
  • The length member of normalizedAlgorithm is zero or is greater than 128
  • The key generation fails

https://www.w3.org/TR/WebCryptoAPI/

With this in mind, I am led to believe the problem is not in your text to be ciphered, but rather on how you are invoking the function.

Another possible cause (albeit, I would not put my money on it) is the fact that encrypting a string that long generates a variable too long for the browser. Check this discussion:

于 2016-04-21T11:22:57.447 回答