0

In my javascript I have a base64 encoded pkcs12 object, which I want to provide as download link. The Pkcs12 (pfx) file to be downloaded is binary data.

So I decoded the object and tried to create an objectUrl from it:

var bin = atob(pkcs12);
var blob = new Blob([bin],
        { type : 'application/x-pkcs12' });
$scope.pkcs12Blob = (window.URL || window.webkitURL).createObjectURL( blob );

The problem is, that the downloaded file is bigger than the original binary data and is not recognized as pkcs12. It looks like as if some utf-8/unicode stuff was introduced into the file.

If I provide the original base64 encoded data to the createObjectURL and download the base64 encoded file, I can decode the downloaded file and get a valid p12 file.

So I am wondering: How does createObjectURL work for binary data?

cornelinux
  • 877
  • 1
  • 9
  • 17
  • 1
    I found this, which worked perfectly: http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript – cornelinux Apr 29 '16 at 10:40
  • If you've figured it out, you can answer your own question http://stackoverflow.com/help/self-answer – Lesley Apr 29 '16 at 11:17

1 Answers1

2

For some reason createObjectURL does not accept a binary string but requires a byte array. This code worked like a charm:

var bytechars = atob($scope.enrolledToken.pkcs12);
var byteNumbers = new Array(bytechars.length);
for (var i = 0; i < bytechars.length; i++) {
    byteNumbers[i] = bytechars.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {type: 'application/x-pkcs12'});
$scope.pkcs12Blob = (window.URL || window.webkitURL).createObjectURL( blob );
cornelinux
  • 877
  • 1
  • 9
  • 17