Coder Social home page Coder Social logo

kjur / jsrsasign Goto Github PK

View Code? Open in Web Editor NEW
3.2K 92.0 644.0 23.09 MB

The 'jsrsasign' (RSA-Sign JavaScript Library) is an opensource free cryptography library supporting RSA/RSAPSS/ECDSA/DSA signing/validation, ASN.1, PKCS#1/5/8 private/public key, X.509 certificate, CRL, OCSP, CMS SignedData, TimeStamp, CAdES and JSON Web Signature/Token in pure JavaScript.

Home Page: https://kjur.github.io/jsrsasign

License: Other

JavaScript 11.08% CSS 0.03% HTML 88.86% Makefile 0.02%
asn1 x509 certificate crl ocsp timestamp cms rsa dsa ecdsa

jsrsasign's Introduction

jsrsasign

license npm version npm downloads jsdeliver downloads CDNJS githubsponsors cryptocurrency

jsrsasign TOP | github | Wiki | DOWNLOADS | TUTORIALS | API REFERENCE | Online Tool | DEMO | NODE TOOL | AddOn | DONATE

The 'jsrsasign' (RSA-Sign JavaScript Library) is an opensource free cryptography library supporting RSA/RSAPSS/ECDSA/DSA signing/validation, ASN.1, PKCS#1/5/8 private/public key, X.509 certificate, CRL, OCSP, CMS SignedData, TimeStamp, CAdES JSON Web Signature/Token/Key in pure JavaScript.

Public page is https://kjur.github.io/jsrsasign .

Your bugfix and pull request contribution are always welcomed :)

NOTICE FOR COMMING 11.0.0 RELEASE

The "jsrsasign" library is a long lived JavaScript library from 2010 developed with old JavaScript style and backword compatibility. From coming release 11.0.0, following are planed and suport them gradually:

  • Stop to support Internet Explorer.
  • Stop to support bower.
  • Modern ECMA functions will be introduced such as Promise, let, Array methods or class.
  • API document generator will be changed from Jsdoc Toolkit to JSDoc3.
  • Module bandler will be used such as browserify or webpack.
  • Not to use YUI compressor.
  • Unit test framework will be changed from QUnit and mocha to jest.
  • W3C Web Crypto API support.
  • split into some modules besides jsrsasign have been all in package before 11.0.0.

NEWS

  • 2024-Jan-16: Security advisory and update for Marvin attack vulnerability published. Due to this vulnerability, RSA PKCS#1.5 and RSAOAEP encryption/decryption no longer be supported.
  • 2023-Mar-12: 10.7.0 Release. Now supports custom X.509 extension and custom OIDs by new "Add-on" architecture. (See here in detail)
  • 2021-Nov-21: 10.5.0 Release. Now supports secp521r1(P-521) ECDSA.
  • 2021-Apr-14: Security advisory and update for CVE-2021-30246 RSA signature validation vulnerability published
  • 2020-Oct-05: jsrsasign won Google Open Source Peer Bonus Award. Thank you Google.
  • 2020-Sep-23: 10.0.0 released for CMS SignedData related class including timestamp and CAdES architecture update
  • 2020-Aug-24: 9.1.0 released to new CRL APIs align with certificate
  • 2020-Aug-19: 9.0.0 released for major update of certificate and CSR generation and parsing without backward compatibility. Please see migration guide in detail.
  • 2020-Aug-02: twitter account @jsrsasign started for announcement. please follow.

HIGHLIGHTS

  • Swiss Army Knife style all in one package crypto and PKI library
  • available on Node.js and browsers
  • Long live open source software from 2010
  • very easy API to use
  • powerful various format key loader and ASN.1 API
  • rich document and samples
  • no dependency to other library
  • no dependency to W3C Web Cryptography API nor OpenSSL
  • no dependency on newer ECMAScirpt function. So old browsers also supported.
  • very popular crypto library with 1M+ npm downloads/month
  • supports "Add-on" architecture

INSTALL

Node NPM

> npm install jsrsasign jsrsasign-util

Bower

> bower install jsrsasign

Or include in HTML from many CDN sites

> <script src="https://cdnjs.cloudflare.com/ajax/libs/jsrsasign/8.0.20/jsrsasign-all-min.js"></script>

USAGE

Loading encrypted PKCS#5 private key:

> var rs = require('jsrsasign');
> var rsu = require('jsrsasign-util');
> var pem = rsu.readFile('z1.prv.p5e.pem');
> var prvKey = rs.KEYUTIL.getKey(pem, 'passwd');

Sign string 'aaa' with the loaded private key:

> var sig = new a.Signature({alg: 'SHA1withRSA'});
> sig.init(prvKey);
> sig.updateString('aaa');
> var sigVal = sig.sign();
> sigVal
'd764dcacb...'

MORE TUTORIALS AND SAMPLES

RECENT SECURITY ADVISORY

published fixed version title/advisory CVE CVSS
2024Jan16 11.0.0 Marvin attack vulnerability for RSA and RSAOAEP decryption CVE-2024-21484 7.5
2022Jun24 10.5.25 JWS and JWT signature validation vulnerability with special characters CVE-2022-25898 ?
2021Apr14 10.2.0 RSA signature validation vulnerability on maleable encoded message CVE-2021-30246 9.1
2020Jun22 8.0.19 ECDSA signature validation vulnerability by accepting wrong ASN.1 encoding CVE-2020-14966 5.5
2020Jun22 8.0.18 RSA RSAES-PKCS1-v1_5 and RSA-OAEP decryption vulnerability with prepending zeros CVE-2020-14967 4.8
2020Jun22 8.0.17 RSA-PSS signature validation vulnerability by prepending zeros CVE-2020-14968 4.2

Here is full published security advisory list.

DONATIONS

If you like jsrsasign and my other project, you can support their development by donation through any of the platform/services below. Thank you as always.

Github Sponsors

You can sponsor jsrsasign with the GitHub Sponsors program.

Cryptocurrency

You can donate cryptocurrency to jsrsasign using the following addresses:

jsrsasign's People

Contributors

adalinesimonian avatar augjoh avatar azeem-r00t avatar cblair avatar clydedcruz avatar cplussharp avatar davedoesdev avatar froatsnook avatar herrjemand avatar ilmesi avatar juanjmarques avatar kgeorgiou avatar kjur avatar kurtsson avatar lionello avatar maxphilips avatar mike-w-kelly avatar mltucker avatar mmalmi avatar nodh avatar parkint avatar peterdavehello avatar raboof avatar ramann avatar samueldiethelm avatar solita-anttihu avatar stephanebachelier avatar t-yuki avatar widcket avatar zboralski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsrsasign's Issues

TypeError: Cannot call method 'bitLength' of undefined\n at RSAKey._rsasign_verifyWithMessageHash [as verifyWithMessageHash] (lib/jsrsasign-4.5.0/npm/lib/jsrsasign.js:251:3675)

Hi,

I am getting this error:
TypeError: Cannot call method 'bitLength' of undefined\n at RSAKey._rsasign_verifyWithMessageHash as verifyWithMessageHash

When I try to verify a PEM certificate. Please note that I am using the npm file directly.

var KJUR = require("cloud/lib/jsrsasign-4.5.0/npm/lib/jsrsasign.js");
var verifier = new KJUR.crypto.Signature({alg: "SHA1withRSA", prov: "cryptojs/jsrsa"});
verifier.initVerifyByCertificatePEM(apple_cert);
verifier.updateString(gc_player_id);
verifier.updateString(app_bundle_id);
verifier.updateHex(gc_timestamp);
verifier.updateHex(gc_salt);
reutrn verifier.verify(gc_unverified_signature);

In the non-minified, non-npm file, I believe the line is rsasign-1.2.js:295

PKCS5PKEY.getEryptedPKCS5PEMFromPrvKeyHex() returns weirdly formatted PEM file

I prepared an example web page here:

https://mowa-net.jp/demos/jsrsasign_exp/index.html

Based on jsrsasign 4.1.2 release.

Look at encrypted rsa pem strings. They won't be decrypted with "openssl rsa" even if we specify the correct password "hogehoge". We can even see the content looks obviously inappropriate

Example:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,101D89EE3900CAFAAF580A3EEB54E1D3

AAAAAHUAAAAUAAAAAAEAAAAAyQAAAwAAAAAAAAAAVwALAAwBDwAAAAAAAAoPAAAA
AAAAAAACAAAPDwAAAGW+AKMEAAAKAAAAAAAAAAAICgAMAAAANgANAAAAAAAAAAAA
AMAAAA+WAJ4AAwAAAAAAAAsAAAoACgwAAAADCg4A7wAOAAEADw8AAAwAAAgAAAAP
CAkADgAPAA4ADAgAAAgAAAAMAAAAAA8AAAAADAAAAAAAAAsAAADRAOwJAAAAowAA
AA8AAAAADAAAAA0AAAAABQAAAAAAAABeAAAAAAAAAAAAAAAAAAABDAD5AAAAAAAA
AAAAAAAAAGkAAAAFDs4AANwAAAAKDJUKAOYABwD6AADdAAAAAAAAAAALAKQAAA0J
AAAKAA0AAA8AAA8OoAsAAAYAAAoAAAAADQwA+QAKAAAAAAAAuQAAAAoAAAAACgAA
AAA7ALXKAAUAAAgDAAAAAAAAAO0ADQAAAAAAngAAAAcAAAAJBgC7DgAP5gAIDA0A
AAAAAAAAAAAADg0OAAgADAANmAAOBA==
-----END RSA PRIVATE KEY-----

There are a lot of 'A's.

The root cause seems that PKCS5PKEY.encryptGeneral() has seemingly wrong logic.

var encryptGeneral = function(f, dataHex, keyHex, ivHex) {
    var data = CryptoJS.enc.Hex.parse(dataHex);
    var key = CryptoJS.enc.Hex.parse(keyHex);
    var iv = CryptoJS.enc.Hex.parse(ivHex);
    var msg = {};
    var encryptedHex = f.encrypt(data, key, { iv: iv });
    var encryptedWA = CryptoJS.enc.Hex.parse(encryptedHex.toString());
    var encryptedB64 = CryptoJS.enc.Base64.stringify(encryptedWA);
    return encryptedB64;
};

It seems this should be

var encryptGeneral = function(f, dataHex, keyHex, ivHex) {
    var data = CryptoJS.enc.Hex.parse(dataHex);
    var key = CryptoJS.enc.Hex.parse(keyHex);
    var iv = CryptoJS.enc.Hex.parse(ivHex);
    return f.encrypt(data, key, { iv: iv }).toString();
};

Confusingly crypto-js's OpenSSLFormatter (see crypto-js's cipher-core.js) returns BASE64 string, not hex, so applying Hex.parse() and Base64.stringify() are inappropriate for that exact case (crypto-js's other formatter does use Hex).

A modified version is here:

https://mowa-net.jp/demos/jsrsasign_exp/mod.html

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,2738243672EA92E5D087AC8FB082014F

PgmtJrgX8WlD2fiESIVIMC7Th2CAITzZNAxMLx9gjnxbzP+CdQF8him3AoeOl4zx
w8LB0JoUvjPqiwGaggv7K9qQLAUSoyEd/IYzGdJdXVrRYk1ZmwZm6c2L4KegdNLE
4+SZ10oU/XKzFkpdzb5cvYRksuje4gLAwR0osC3FS7LzJF2/hhmDmf6Lh7DWxdWF
/VxiqYvq3RswOldLwvLQjcmdE4OrRk2TCiYy/Hr3FjIApVQe0xRu7oM86kIExNB0
QNq2shu37pOTRMjaIlFeBvC8rZDDmmlC1T+IntXkaZalt4k49HlGea1PzHFPku9w
YLXKPxkl+sLVhojN2Lpm9D+OWubLMNgZrY6N6wnEF2mErYcstbL8q0FCfnJnpg+1
GEGxhnRVX8kPWBE1g24EEJcCfVj8ks5R2sRj9wotEBCOuQw3A1hEVFlbhwJ2xsKK
6q9BXUba3m8yCaV5Ldga0bkD9VfImN08iE0SHTPIWMIgMv4bqU//5COxkz9Fm1se
vvdDW99hg4KwDjVwBm9wcvwgq2wAT54voC5KVW1QGMeYuZMyAeGeQL7RbLkoLcNL
Pe2l8Gtzl2GHXPJKsMZbeYvggrol7mVVOogXSqlJXVxb9drHCSt2mNxv6BafXo+o
kwL00Fw4YrcCeq3msog19QV6qHcW9iH6QzjKSNnoZhKRuOxpmBxEelQX1tEJF412
DMOKCh/pBLXI2O99shbRx6vjb98HB79TPJrd5Jm+GGJLChpYRqOIPn0GP37nvZTN
sCEHy0S0x8OP45Nap01GOMWZf8JmpAMBTvtKCVMVrA4=
-----END RSA PRIVATE KEY-----

This can be decrypted with "openssl rsa"

PHP/OpenSSL Compatibility

Hi there,

I am trying to check the signature generated by the sample from
http://kjur.github.io/jsrsasign/sample-rsasign.html
in PHP.
openssl_verify should return 1 if the signature is correct. It returns 0 however, which means the signature is invalid. Here is my code:

$pubkey = "
-----BEGIN CERTIFICATE-----
MIIBvTCCASYCCQD55fNzc0WF7TANBgkqhkiG9w0BAQUFADAjMQswCQYDVQQGEwJK
UDEUMBIGA1UEChMLMDAtVEVTVC1SU0EwHhcNMTAwNTI4MDIwODUxWhcNMjAwNTI1
MDIwODUxWjAjMQswCQYDVQQGEwJKUDEUMBIGA1UEChMLMDAtVEVTVC1SU0EwgZ8w
DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANGEYXtfgDRlWUSDn3haY4NVVQiKI9Cz
Thoua9+DxJuiseyzmBBe7Roh1RPqdvmtOHmEPbJ+kXZYhbozzPRbFGHCJyBfCLzQ
fVos9/qUQ88u83b0SFA2MGmQWQAlRtLy66EkR4rDRwTj2DzR4EEXgEKpIvo8VBs/
3+sHLF3ESgAhAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAEZ6mXFFq3AzfaqWHmCy1
ARjlauYAa8ZmUFnLm0emg9dkVBJ63aEqARhtok6bDQDzSJxiLpCEF6G4b/Nv/M/M
LyhP+OoOTmETMegAVQMq71choVJyOFE5BtQa6M/lCHEOya5QUfoRF2HF9EjRF44K
3OK+u3ivTSj3zwjtpudY5Xo=
-----END CERTIFICATE-----
";

var_dump(openssl_verify("aaa", hex2bin("6f7df91d8f973a0619d525c319337741130b77b21f9667dc7d1d74853b644cbe5e6b0e84aacc2faee883d43affb811fc653b67c38203d4f206d1b838c4714b6b2cf17cd621303c21bac96090df3883e58784a0576e501c10cdefb12b6bf887e548f6b07b09ae80d8416151d7dab7066d645e2eee57ac5f7af2a70ee0724c8e47"), openssl_pkey_get_public($pubkey), "sha1WithRSAEncryption"));

Best regards,

Manuel

Minor bug found in signStringWithXXX

Here below is the fix.

function _rsasign_signStringWithSHA1(s) {

  • return _rsasign_signString(s, 'sha1');
  • return _rsasign_signString.call(this, s, 'sha1');^M
    }

function _rsasign_signStringWithSHA256(s) {

  • return _rsasign_signString(s, 'sha256');
  • return _rsasign_signString.call(this, s, 'sha256');^M
    }

Regards,

Error "this.n is undefined" when verifying signature

I have the following code:

var signer = new KJUR.crypto.Signature({ 'alg': 'SHA1withRSA', 'prov': 'cryptojs/jsrsa' });
signer.initVerifyByCertificatePEM('-----BEGIN PUBLIC KEY-----\n' +
'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALvU5TrNPuQ8bgZp0ou+PvKqTpZJ6lS6\n' +
'WpNOkIt2hncaHBpPFxCU3h1Y+sXtaY1mqZC30yj6q4KHZAwcuN9R3BMCAwEAAQ==\n' +
'-----END PUBLIC KEY-----');
signer.updateString('Some string hello world.');
if(!signer.verify(signature))
    alert('Signature Invalid!');

(Note that this is a 512-bit key.) This conforms to the example in the tutorial. The code works fine up until the point it calls signer.verify(signature). Then I get the error "this.n is undefined."

I traced it down to the fact that initVerifyByCertificatePEM sets the public key to an x509, which has no n property. Calling verify ultimately attempts to use the n property, but n is only present in RSAKey. I can set the public key to an RSAKey by calling initVerifyByPublicKey (instead of initVerifyByCertificatePEM) but that presents another problem: You can't create an RSAKey with just the encoded public key. You have to have the private key.

Since I'm just testing this right now and have access to private key, this is OK. I can successfully verify the signature as long as I have the private key RSAKey. But there doesn't appear to be a way to verify a signature with just the encoded public key string available.

Uncaught exception in KEYUTIL.getPEM

In example sample-rsasign.html, include:

<script language="JavaScript" type="text/javascript" src="keyutil-1.0.js"></script>

Then add getPEM function into the doSign() function:

function doSign() {
  var rsa = new RSAKey();
  rsa.readPrivateKeyFromPEMString(document.form1.prvkey1.value);

  ///////  causes uncaught exception /////
  var pem = KEYUTIL.getPEM(rsa);
  alert("pem:" + pem );
  ////////////////////////////////////////

  var hashAlg = document.form1.hashalg.value;
  var hSig = rsa.signString(document.form1.msgsigned.value, hashAlg);
  document.form1.siggenerated.value = linebrk(hSig, 64);
}

I get error: "uncaught exception: unsupported object nor format"

Unable to get PEM using KEYUTIL.getPEM.

This is my code:

var rsa = require("jsrsasign");
var keypair = rsa.KEYUTIL.generateKeypair("RSA", 256);
console.log(keypair.prvKeyObj);
console.log(rsa.KEYUTIL.getPEM(keypair.prvKeyObj)); // ERROR

It results in this error:

Uncaught unsupported object nor format

keypair.prvKeyObj is a RSAKey object, and I believe that is what the rsa.KEYUTIL.getPEM method accepts basedon the docs. Why might I be getting this error?

Demo application script references

The demo application at the public site references version 1 scripts even though the scripts are at version 1.1, so it is not working!

Fix Demo Page

The demo page currently fails with this error in chrome:

Uncaught ReferenceError: KJUR is not defined 

I assume a file is missing, but unsure which.

when calling JWS.generateJWSByNED, has no method 'isSafeJSONString'

when create a signature by RSA-SHA256 algorithm,I have got an error.

It was the message of "TypeError: Object [object Object] has no method 'isSafeJSONString'"

The following are the steps.

$ npm install jsrsasign

$ node

> var r = require('jsrsasign');

> var header = '{"alg":"RS256"}';

> var payload = '{"iss":"joe", "exp":1300819380, "http://example.com/is_root":true}';

> var jwk =   {"kty":"RSA",
    "n":"ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ",
    "e":"AQAB",
    "d":"Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97IjlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0BkTGoVEn2bKVRUCgu-6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYTCBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLhBOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ"
};

> var n = r.b64tohex(jwk['n']);

> var d = r.b64tohex(jwk['d']);

> var e = r.b64tohex(jwk['e']);

> var jws = new r.jws.JWS();

> var signature = jws.generateJWSByNED(jwsHeader, jwsPayload, n, e, d);
TypeError: Object [object Object] has no method 'isSafeJSONString'
    at generateJWSByNED (/Users/hiyosi/code/rsa-sign/node_modules/jsrsasign/lib/jsrsasign.js:258:2624)
    at repl:1:5
    at REPLServer.self.eval (repl.js:110:21)
    at repl.js:249:20
    at REPLServer.self.eval (repl.js:122:7)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)

KEYUTIL.generateKeypair("RSA") private key not isPrivate

Hi, just using your library. I think i've detected a bug,

When i generate the keypair of RSA, and after that i try to getPEM() of them, the public is working fine, but private doesn't work. Searching for that, i've found that isPrivate is not set to true on the prvObjKey when generating the keys.

I've solved the problem on my code by adding prvkey.isPrivate = true, but i think the constructor of keys must do that automatically,

Correct me if i'm wrong :)

Thank you!

Release version

Hello,

Sorry to bother again. Is there an official, minified version of your library in your repository?

Best,
Louis

No mention about YUI 2.9.0 dependency

Some of files implicitly depend on YUI 2.9.0 while there's no mention here (and in the original project page). It would be better to mention it like CryptoJS.

How to build?

I made some modifications and wanted to test the built output. Is there a script to minify and create the jsrsasign-latest-all-min.js? Or can you provide one?

Thank you!

Trying to init a Signature object from keypair generated by KEYUTIL.generateKeypair fails.

I'm passing in a RSAKey object to Signature.init() and it fails with

Uncaught init failed.:[object Object]

My code looks like this:

           // in browser, using browserify.
            var rsa = require("jsrsasign");
            var keypair = rsa.KEYUTIL.generateKeypair("RSA", 256);
            console.log(keypair.prvKeyObj);
                var signature = new rsa.Signature({alg: "MD5withRSA"});
                signature.init(keypair.prvKeyObj); // ERROR HERE
                    signature.updateString("Hello");
                    var signatureValue = signature.sign();
                    console.log(signatureValue);

Why might the init fail?

[enhancement] Add missing bower.json.

Hey, maintainer(s) of kjur/jsrsasign!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library kjur/jsrsasign is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "kjur/jsrsasign",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Allow for variations in PEM headers in KEYUTIL

Like using a RegExp for example:

    getHexFromPEM: function(sPEM, sHead) {
    var s = sPEM;
        var regex = new RegExp("BEGIN\\s*" + sHead);
    if (regex.test(s)) {
    throw "can't find PEM header: " + sHead;
    }
    s = s.replace("-----BEGIN " + sHead + "-----", "");
    s = s.replace("-----END " + sHead + "-----", "");
    var sB64 = s.replace(/\s+/g, '');
        var dataHex = b64tohex(sB64);
    return dataHex;
},

Moving EC Keys Into BouncyCastle

Hello,

I need to be able to move EC Keys between this Javascript Library and BouncyCastle APIs. I'm a bit confused as to what format the basic JS functionality generates and how to reconstitute them in Java(and vice versa).

for instance to build a Public Key in bouncy castle I take a hex string via

keypair = ec.generateKeyPairHex();
prvkey = keypair.ecprvhex;

byte[] publicKeyFromJSArray = Hex.decodeHex(publicKeyHexFromJavascript.toCharArray()); // this is the prvkey String

    ECPoint pubPoint = ecSpec.getCurve().decodePoint(publicKeyFromJSArray);
    org.bouncycastle.jce.spec.ECPublicKeySpec pubKeySpec2 = new ECPublicKeySpec(  pubPoint,
             ecSpec); 
    PublicKey pubkey2 = fact.generatePublic(pubKeySpec2);

I later attempt to make a signature with it and it fails. Any idea how to do this?

thanks! -bm

AuthorityKeyIdentifier extension

I need to add the extension AuthorityKeyIdentifier to my certificate. I have created a function to handle it, similar to the existing ones :

//'authorityKeyIdentifier', 'keyid', critical=False, issuer=self.context.x509

tbsc.appendExtension(new KJUR.asn1.x509.AuthorityKeyIdentifier({'keyIdentifier': 'keyid','authorityCertIssuer':oIssuer , 'critical':false}));

But, the code I did it is showing the extension with an empty content. Could you please add this extension to the next version? Thanks a lot in advance.

Cheers,
Andres

Missing OID elements

There are two parameters missing that we have added during testing to the version we have and they are working fine. The function is KJUR.asn1.x509.OID and the list is atype2oidList from the asn1x509-1.0.js.

The two parameters missing are:
'DN': '2.5.4.49',
'DC': '0.9.2342.19200300.100.1.25',

They are present is some certificates. Without them, the conversion tools are failing when analyzing those certificates.

Trouble generating keys

I was having trouble generating keys.

In RSAGenerate(B, E), I changed this line:

var ee = new BigInteger(E,16);

to:

var ee = new BigInteger(E,16,rng);

That made it work. I've contacted Tom Wu to ask but was wondering whether you've seen this problem?

Fix typo in KEYUTIL newEncryptedPKCS5PEM

Need to use "pKey' for params in getEncryptedPKCS5PEMFromRSAKey below:

if (typeof alg == "undefined" || alg == null) {
pem = this.getEncryptedPKCS5PEMFromRSAKey(pkey, passcode);
} else {
pem = this.getEncryptedPKCS5PEMFromRSAKey(pkey, passcode, alg);
}

Request to remove dependency on yahoo

Because some crypto functions take a long time to run, I wanted to put them into a worker thread using HTML5 Web Workers.

However, the "yahoo-min.js" script which is packaged into "jsrsasign-latest-all.js" contains unnecessary references to the "window" object (open window in a browser)...which does not exist in the Web Worker context, and prevents it from being able to run there.

It would be nice to remove this dependency on yahoo anyway as it is unclear why it should be there

bf-ofb rsa key

Hello, can i decrypt key was maden with blowfish (OFB mode) encryption?
I was trying to implement it, but have no success... I am just a novice in cryptography...

As I understand this key is PKCS#5 format also, so I just need add the following processor to ALGLIST

'BF-OFB': { 'proc': decryptBF, 'eproc': encryptBF, keylen: 16, ivlen: 8 }

and then decrypt data given to decryptBF (dataHex, keyHex, ivHex)

Maybe you know a good library for blowfish decryption?

xml signing issue in jsrsasign?

I am signing XML (SAML) using the jsrsasign library, using KJUR. I have the "SHA1withRSA" signing and validation set up per the Signature tutorial, and validation is returning as being valid. But when the signed XML is sent, the server cannot validate.

(I have this signing working with nodeJS using the xml-crypto plugin, but nodeJs uses its own built-in crypto. I am trying to use this outside of nodeJS, and therefore replacing the crypto library with jsrsasign)

Is there a limitation using these libraries when creating XML digital signatures? I think the xml string i'm signing is 650+ chars.

Is this something that "progressive signing" would solve? I can't seem to find any documentation on it other than the part mentioned in the tutorial.

How to accomplish the openssl commands below with your module?

Hi,

Can you please tell me if it is possible to accomplish what the below code is doing in openssl with your module?

I'm basically trying to use my own CA which I already created to create and sign a pk12 format compatible S/MIME certificate.

sudo openssl genrsa -out smime.key 2048
sudo openssl req -new -config ../openssl.cnf -key smime.key -out smime.csr
sudo openssl x509 -req -days 365 -in smime.csr -CA ../cacert.pem -CAkey ../private/cakey.pem -set_serial 1 -out smime.crt -setalias "Self Signed SMIME" -addtrust emailProtection -addreject clientAuth -addreject serverAuth -trustout -extfile ../openssl.cnf -extensions mail_ext
sudo openssl pkcs12 -export -in smime.crt -inkey smime.key -out smime.p12

Thank you in advance,
Tony Yustein

Document utf8 assumption for MesssageDigest string API.

I see that both cryptojs and sjcl encodes strings as utf8 before hashing. It would be a nice-to-have to document this in the string APIs.

So if strings are used to keep an array of 8-bit values, the hex interface must be used.

RSA signing sample does not work

TypeError: KJUR.crypto.Util.hashString is not a function

var hashFunc = function(s) { return KJUR.crypto.Util.hashString(s, hashAlg); };

rsasign-1.2.js (line 67)

How to convert the content of a DER formatted file to a PEM formatted String

Hello!

I've been using your project with the FileReader API to read a certificate in order to extract the subject as a String, i alreay read your documentation, but I'm a little lost. I would like to know if there's a way to convert the DER formatted content of a file to a PEM formatted string?

As an extra info: im using the function readAsBinaryString (https://developer.mozilla.org/en-US/docs/Web/API/FileReader)

Thanks for your time in advance. Greetings!

pkcs#8 DER binary input file

Hi, frist of all thanks for you great job, well now I'm using this code quite similar to your function

function doSign2() {
var rsa = new RSAKey();
rsa.readPrivateKeyFromPEMString(document.form1.prvkey1.value);
var hashAlg = document.form1.hashalg.value;
var hSig = rsa.signString(document.form1.msgsigned.value, hashAlg);
return hSig;
}; hex2b64(doSign2());

but before to make this I'm using the openSSL tool for converting from pkcs#8 DER to pkcs#1 just like this

openssl pkcs8 -inform DER -outform PEM -in xxx.key -out xxx_pem.key

and then this

openssl rsa -in "xxx_pem.key" -out xxx_pem_rsa.key

I've been reading the documentation and I really feel a little bit lost, I'm trying to convert the binary file to Hex and using this code that you provide in an issue before but I really don't know how to use it

var rawDerFileContents = "..........";
var hexDerFileContents = rstrtohex(rawDerFileContents); // raw string to hex
var pemString = KJUR.asn1.ASN1Util.getPEMStringFromHex(hexDerFileContents, "CERTIFICATE"); // with PEM Header

Thanks

is this a bug in rsa signature?

this message & this private key generate the incorrect signature:

message = "0.138 0.518 0.477 0.488 0.061 0.056 0.832 0.284 0.714 0.862" (omit quotes when testing)

private key:

-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDRMDd5hqSX6WPbeu1gqe10IEACruFZkHSWAQzBC/SEqk67qSOU
Zstd0hIum7sUk6RsMgPLKTscSWNxtyC1xD4TyvFqx+gMdCXLciV3dj/mUK+mFEl/
/D+1u5pHi2LpBuN2/wRY+Zfc/DBien7Ppa7hlS60YWtuW3dp4s0ZpqK0JQIDAQAB
AoGASSfKjrZWg0W8hTn1H9PtVaodmJKd/lt1Wiwd0LkkluyUQi6BYdmdDz9y2lfd
0fFcE/Zdu0O9B0RnAZKgXtC1QEbTWiPhg80lGrP6BUWd7qCnojzOjXTOaM3h42K6
FXdwYZsM5nAfhIRjjzpNG4fLUkytFP/noHQPW6vuwy3KmYECQQDtph1dJgJJueAI
qDKOR0eIpoRAKXzjHBY/g5VSS7q7CI/zIerzO6DHQ8KlgXrvful/tuP+UQ2C+4rD
PanOFTMFAkEA4Vd9MAJCHm/8sNhMzqWjJGgh23GPRlsbi0tNhUkV0UebMufxM8+C
4QFFNpN872Ox+355ja+20qfFkyPnfYWGoQJBAJ/54+hxjra8poCNYUL/3rqxhXN/
ui9UF/H3jQxSKEiBkg2Udon4SNn61kv9ppkUMPElV8M6IsNau2WE3Ar7oFUCQAbf
k0r2lqu1AMEoJ9eZx8shff7ijNs5hjKOfnPVUdwLUhmQZ5QL/VL9pe3PO91VbiVc
qzp+JJZyVZ1yV+pFO2ECQQDN4QAVG53tRibrmJivWfsbiRKrcixr53Lq/8S6m9Gv
DkzXXUYfl0g3mDr768rV065PUNFYaoqfAKiZxeBwIu7p
-----END RSA PRIVATE KEY-----

i believe the correct signature is:

51c7b9944be73e58917a993d78fe7ccd35a240ce50ae6f2990789caa95d0c4c983ce51025ecb3d7f95fe8956995880614b40e86e873c4d3b89e3cbe289675e14cca6309a1e7339b178a1c62c0ad4461b0156b785690fc787681318fb24ae5a72af83f06fa10e9fb638efc07e7d145397218e1dd85f09011df4603d26bb0f5147

however, this library generates the following:

1804ce651ad8f116759f570ba4ef3f9d23c14de4b296417aaebf33679a4ba44897bbcac701167f3f12fb1d58d16dbef267ba524a89c41f2884691b88c73469a8eba0b255b868521dbd194e62399302508f6898addd79e79713091f2b5bc0554aee3d6402aa26d8eaec6b1e694d2680f8a2c4a84bb86a3303387d947dfaef012a

seems to be related to the length, in characters, of the message being signed. smaller message lengths seem to work well.

i generated the "correct" signature using the node.js crypto library, based on openssl.

Seeding the PRNG

I needed to seed the PRNG with a specific value. After some poking around I found that it can be done like so:

function hex2Array(hex)
{
var arr = new Array();
for (var i = 0; i < hex.length; i += 2)
arr[i/2] = parseInt(hex.substr(i, 2), 16);
return arr;
}

var seedByteArray = hex2Array(seedHexStr);

////////////////
rng_state = prng_newstate();
rng_state.init(seedByteArray);
///////////////

It might be nice to add these last two lines into a "seed" function of the SecureRandom class in the future

Create PEM formatted RSA public key string from RSA Public Key

Hello,
I would like to ask for a method that creates the PEM formatted RSA public key string from RSA Public Key. This is the opposite of KJUR.asn1.x509.SubjectPublicKeyInfo.setRSAPEM in asn1x509-1.0.js.

Or, I could try implementing it. I just need some tips.
Thanks!
Miguel

version 1 not supported

It appears that x509 version 1 certificates are not supported. Can you please consider adding support for this.

PSS verification - padding bug?

I am using jsrsasign-latest-all-min.js

  1. I compute PSS signature:

var msg = "hello";
var sig = rsa.signStringPSS(msg, "sha1");

  1. I try to verify:

console.log("verified: " + rsa.verifyStringPSS( msg, sig, "sha1" ) );

Error: on line 389 of rsasign-1.2.js, "encoded message does not end in 0xbc";

Let me know if you have any difficulty reproducing

  1. I think there may be another error, because the signature given by this method cannot be validated using Crypto++ signature scheme RSASS<PSS, SHA1>, which is the same scheme

How to accomplish the openssl commands below with your module?

Hi,

Can you please tell me if it is possible to accomplish what the below code is doing in openssl with your module?

I'm basically trying to use my own CA which I already created to create and sign a pk12 format compatible S/MIME certificate.

sudo openssl genrsa -out smime.key 2048
sudo openssl req -new -config ../openssl.cnf -key smime.key -out smime.csr
sudo openssl x509 -req -days 365 -in smime.csr -CA ../cacert.pem -CAkey ../private/cakey.pem -set_serial 1 -out smime.crt -setalias "Self Signed SMIME" -addtrust emailProtection -addreject clientAuth -addreject serverAuth -trustout -extfile ../openssl.cnf -extensions mail_ext
sudo openssl pkcs12 -export -in smime.crt -inkey smime.key -out smime.p12

Thank you in advance,
Tony Yustein

RSAKey.generate generates guessable keys

I looked through the SecureRandom code and it doesn't look very good compared to sjcl or forge.

rng.js contains the following comment at the top of the file:

// For best results, put code like
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>

And then further down:

// TODO: allow reseeding after first request

The issue is that the rng_pool array is never touched after initializing the RC4 prng in prng4.js, so no entropy can be added to the system.

The other serious issue is that the rng does not use window.crypto.getRandomValues():

This means that Math.random() and the current time (once!) are the only sources of entropy.

http://stackoverflow.com/questions/578700/how-trustworthy-is-javascripts-random-implementation-in-various-browsers

Given that we must assume Math.random() has maybe 32-bit entropy, and the current time (milliseconds) must give << 10 bits of entropy, then it is likely that the generated RSA key space is easy to enumerate and thus the generated keys are useless.

Probably the files rng.js and prng4.js should be removed and replaced by something that is actively maintained. It is easy to add support for getRandomValues() but there are other prngs that are both maintained and provide additional entropy sources.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.