Anatoliy
Anatoliy

Reputation: 30103

Sign data using private key on client-side (javascript)

I know, it looks strange, but I need to sign some data on client-side using javascript only, no ajax backdoor to server-side openssl available. Could someone suggest some client-side solution to sign data using private key? Is it possible?

Thanks.

Upvotes: 11

Views: 21144

Answers (5)

rebinnaf
rebinnaf

Reputation: 513

You can use jose

    import * as jose from 'jose'
    const privateKey= '449f9c8d5a4b71c829f2f670965bd67fd5332a146019r0870a2a659e114c185d'
    const SECRET_KEY = new TextEncoder().encode(privateKey)
    const payload = {
      params: {
        example: 'Hi'
      }
    }
    const alg = 'HS256'
    const token = await new jose.SignJWT(payload)
      .setProtectedHeader({ alg })
      .setIssuedAt()
      .setIssuer('urn:example:issuer')
      .setAudience('urn:example:audience')
      .setExpirationTime('2h')
      .sign(SECRET_KEY)

Note: If you put the privateKey in js client, it is indeed insecure.

Upvotes: 0

RT Denver
RT Denver

Reputation: 74

Web Crypto appears to be the answer. Here is a tutorial (not mine). As for the comment, if you are using https, why do you need signing - these are needed for two different purposes. In infosec lingo, the former gives confidentiality and the latter non-repudiation.

Upvotes: 0

Kevin Hakanson
Kevin Hakanson

Reputation: 42220

The W3C Web Cryptography API may be able to help. Can I use indicates modern browsers now support it.

For additional digital signature support, look at GlobalSign/PKI.js

PKIjs is a pure JavaScript library implementing the formats that are used in PKI applications (signing, encryption, certificate requests, OCSP and TSP requests/responses). It is built on WebCrypto (Web Cryptography API) and requires no plug-ins. http://pkijs.org

Upvotes: 3

Anatoliy
Anatoliy

Reputation: 30103

Found great signing tool. It implements RSA-SHA1 (works perfectly) and RSA-SHA256 (works strange), and allow both to generate signature using private key and to verify signature using certificate.

Upvotes: 6

user578895
user578895

Reputation:

I've gone down the same road as you, you're probably better off implementing something like oAuth.

The problem with what you're proposing is that there's absolutely no reliable way of storing the private key on the client machine, nor of now securely getting the public key back to the server other than HTTPS (and if you're using HTTPS, what's the point of this?)

If you really want to continue, there are some implementations out there: http://shop-js.sourceforge.net/crypto2.htm

And you probably want something horribly annoying like PersistJS (http://pablotron.org/?cid=1557) to try and save the private key as long as possible.

Upvotes: 1

Related Questions