summaryrefslogtreecommitdiff
path: root/js/dojo-1.7.2/dojox/encoding/crypto/RSAKey.js
blob: be1707c44c1a00432a88c6d4f9dd75d9c1dd19f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//>>built
define("dojox/encoding/crypto/RSAKey", [
	"dojo/_base/kernel",
	"dojo/_base/declare",
	"../../math/BigInteger",
	"../../math/random/Simple"
], function(kernel, declare, BigInteger, Simple) {

	kernel.experimental("dojox.encoding.crypto.RSAKey");

// Copyright (c) 2005  Tom Wu
// All Rights Reserved.
// See "LICENSE-BigInteger" in dojox.math for details.

	var defaultRngf = function(){ return new Simple(); };

	// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
	function pkcs1pad2(s, n, rngf) {
		if(n < s.length + 11) {
			throw new Error("Message too long for RSA");
		}
		var ba = new Array(n);
		var i = s.length;
		while(i && n) ba[--n] = s.charCodeAt(--i);
		ba[--n] = 0;
		var rng = rngf();
		var x = [0];
		while(n > 2) { // random non-zero pad
			x[0] = 0;
			while(x[0] == 0) rng.nextBytes(x);
			ba[--n] = x[0];
		}
		ba[--n] = 2;
		ba[--n] = 0;
		rng.destroy();
		return new BigInteger(ba);
	}

	return declare("dojox.encoding.crypto.RSAKey", null, {
		constructor: function(rngf){
			// summary:
			//	"empty" RSA key constructor
			// rndf: Function?:
			//	function that returns an instance of a random number generator
			//	(see dojox.math.random for details)
			this.rngf = rngf || defaultRngf;
			this.e = 0;
			this.n = this.d = this.p = this.q = this.dmp1 = this.dmq1 = this.coeff = null;
		},

		setPublic: function(N, E){
			// summary:
			//	Set the public key fields N and e from hex strings
			if(N && E && N.length && E.length) {
				this.n = new BigInteger(N, 16);
				this.e = parseInt(E, 16);
			}else{
				throw new Error("Invalid RSA public key");
			}
		},

		encrypt: function(text){
			var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3, this.rngf);
			if(!m){
				return null;
			}
			var c = m.modPowInt(this.e, this.n);
			if(!c){
				return null;
			}
			var h = c.toString(16);
			return h.length % 2 ? "0" + h : h;
		}
	});
});