Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: lib/rsa.js

Issue 29354773: Issue 4465 - Move rsa module from adblockpluschrome (Closed)
Patch Set: Add unit tests Created Sept. 23, 2016, 1:45 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « lib/jsbn.js ('k') | lib/rusha.js » ('j') | test/signatures.js » ('J')
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /*
2 * This file is part of Adblock Plus <https://adblockplus.org/>,
3 * Copyright (C) 2006-2016 Eyeo GmbH
4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation.
8 *
9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 /**
19 * This is a specialized RSA library meant only to verify SHA1-based signatures.
20 */
21
22 let {BigInteger} = require("jsbn");
23 let Rusha = require("rusha");
24
25 let rusha = new Rusha();
26
27 // Node.Js does not include atob, but we can make use of Buffer
28 if (typeof atob == "undefined" && typeof Buffer != "undefined")
29 global.atob = data => new Buffer(data, "base64").toString("binary");
kzar 2016/09/23 13:48:45 If I simply did `var atob = ...` here the tests br
Wladimir Palant 2016/09/23 20:02:29 atob() is defined on the window object, and Node d
kzar 2016/09/25 12:46:47 Good point. I already did a bunch of similar work[
Wladimir Palant 2016/09/25 13:02:28 sandboxed-module seems to be a cleaner solution to
30
31 // Define ASN.1 templates for the data structures used
32 function seq()
33 {
34 return {type: 0x30, children: Array.prototype.slice.call(arguments)};
35 }
36 function obj(id)
37 {
38 return {type: 0x06, content: id};
39 }
40 function bitStr(contents)
41 {
42 return {type: 0x03, encapsulates: contents};
43 }
44 function intResult(id)
45 {
46 return {type: 0x02, out: id};
47 }
48 function octetResult(id)
49 {
50 return {type: 0x04, out: id};
51 }
52
53 // See http://www.cryptopp.com/wiki/Keys_and_Formats#RSA_PublicKey
54 // 2A 86 48 86 F7 0D 01 01 01 means 1.2.840.113549.1.1.1
55 var publicKeyTemplate = seq(seq(obj("\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01"), {}) , bitStr(seq(intResult("n"), intResult("e"))));
56
57 // See http://tools.ietf.org/html/rfc3447#section-9.2 step 2
58 // 2B 0E 03 02 1A means 1.3.14.3.2.26
59 var signatureTemplate = seq(seq(obj("\x2B\x0E\x03\x02\x1A"), {}), octetResult("s ha1"));
60
61 /**
62 * Reads ASN.1 data matching the template passed in. This will throw an
63 * exception if the data format doesn't match the template. On success an
64 * object containing result properties is returned.
65 *
66 * See http://luca.ntop.org/Teaching/Appunti/asn1.html for info on the format.
67 */
68 function readASN1(data, templ)
69 {
70 var pos = 0;
71 function next()
72 {
73 return data.charCodeAt(pos++);
74 }
75
76 function readLength()
77 {
78 var len = next();
79 if (len & 0x80)
80 {
81 var cnt = len & 0x7F;
82 if (cnt > 2 || cnt == 0)
83 throw "Unsupported length";
84
85 len = 0;
86 for (var i = 0; i < cnt; i++)
87 len += next() << (cnt - 1 - i) * 8;
88 return len;
89 }
90 else
91 return len;
92 }
93
94 function readNode(curTempl)
95 {
96 var type = next();
97 var len = readLength();
98 if ("type" in curTempl && curTempl.type != type)
99 throw "Unexpected type";
100 if ("content" in curTempl && curTempl.content != data.substr(pos, len))
101 throw "Unexpected content";
102 if ("out" in curTempl)
103 out[curTempl.out] = new BigInteger(data.substr(pos, len), 256);
104 if ("children" in curTempl)
105 {
106 var i, end;
107 for (i = 0, end = pos + len; pos < end; i++)
108 {
109 if (i >= curTempl.children.length)
110 throw "Too many children";
111 readNode(curTempl.children[i]);
112 }
113 if (i < curTempl.children.length)
114 throw "Too few children";
115 if (pos > end)
116 throw "Children too large";
117 }
118 else if ("encapsulates" in curTempl)
119 {
120 if (next() != 0)
121 throw "Encapsulation expected";
122 readNode(curTempl.encapsulates);
123 }
124 else
125 pos += len;
126 }
127
128 var out = {};
129 readNode(templ);
130 if (pos != data.length)
131 throw "Too much data";
132 return out;
133 }
134
135 /**
136 * Reads a BER-encoded RSA public key. On success returns an object with the
137 * properties n and e (the components of the key), otherwise null.
138 */
139 function readPublicKey(key)
140 {
141 try
142 {
143 return readASN1(atob(key), publicKeyTemplate);
144 }
145 catch (e)
146 {
147 console.log("Invalid RSA public key: " + e);
148 return null;
149 }
150 }
151
152 /**
153 * Checks whether the signature is valid for the given public key and data.
154 */
155 function verifySignature(key, signature, data)
156 {
157 var keyData = readPublicKey(key);
158 if (!keyData)
159 return false;
160
161 // We need the exponent as regular number
162 keyData.e = parseInt(keyData.e.toString(16), 16);
163
164 // Decrypt signature data using RSA algorithm
165 var sigInt = new BigInteger(atob(signature), 256);
166 var digest = sigInt.modPowInt(keyData.e, keyData.n).toString(256);
167
168 try
169 {
170 var pos = 0;
171 function next()
172 {
173 return digest.charCodeAt(pos++);
174 }
175
176 // Skip padding, see http://tools.ietf.org/html/rfc3447#section-9.2 step 5
177 if (next() != 1)
178 throw "Wrong padding in signature digest";
179 while (next() == 255) {}
180 if (digest.charCodeAt(pos - 1) != 0)
181 throw "Wrong padding in signature digest";
182
183 // Rest is an ASN.1 structure, get the SHA1 hash from it and compare to
184 // the real one
185 var sha1 = readASN1(digest.substr(pos), signatureTemplate).sha1;
186 var expected = new BigInteger(rusha.digest(data), 16);
187 return (sha1.compareTo(expected) == 0);
188 }
189 catch (e)
190 {
191 console.log("Invalid encrypted signature: " + e);
192 return false;
193 }
194 }
195 exports.verifySignature = verifySignature;
OLDNEW
« no previous file with comments | « lib/jsbn.js ('k') | lib/rusha.js » ('j') | test/signatures.js » ('J')

Powered by Google App Engine
This is Rietveld