2016-10-03 23:15:21 +11:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const BN = require('asn1.js').bignum
|
2017-01-16 05:17:50 +01:00
|
|
|
const Buffer = require('safe-buffer').Buffer
|
2016-10-03 23:15:21 +11:00
|
|
|
|
|
|
|
// Convert a BN.js instance to a base64 encoded string without padding
|
|
|
|
// Adapted from https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#appendix-C
|
2017-04-11 10:14:00 +01:00
|
|
|
exports.toBase64 = function toBase64 (bn, len) {
|
|
|
|
// if len is defined then the bytes are leading-0 padded to the length
|
|
|
|
let s = bn.toArrayLike(Buffer, 'be', len).toString('base64')
|
2016-10-03 23:15:21 +11:00
|
|
|
|
|
|
|
return s
|
|
|
|
.replace(/(=*)$/, '') // Remove any trailing '='s
|
|
|
|
.replace(/\+/g, '-') // 62nd char of encoding
|
|
|
|
.replace(/\//g, '_') // 63rd char of encoding
|
|
|
|
}
|
|
|
|
|
|
|
|
// Convert a base64 encoded string to a BN.js instance
|
|
|
|
exports.toBn = function toBn (str) {
|
|
|
|
return new BN(Buffer.from(str, 'base64'))
|
|
|
|
}
|