javascript - How do I encrypt Crypto-JS keys with JSBN? -
i'm using jsbn encrypt/decrypt data using public/private keypairs. works great text data, including hex strings.
my problem have binary data, crypto-js word arrays, need encrypt public key , send along platform.
so consider this:
var key = cryptojs.lib.wordarray.random(256/8); var rsa = new rsakey(); rsa.setpublic(modulus, exponent); var encrypted_key = rsa.encrypt(key.tostring()); this works means 'encrypted_key' infact hex string that's been encrypted, not actual key. need encrypt actual key.
so see 2 challenges here:
1) i'm not 100% sure how actual bytes out of cryptojs.lib.wordarray -- though doesn't seem totally insurmountable.
2) have no idea if it's possible encrypt binary data using jsbn. i'd love pointers figure out how it.
any thoughts?
the jsbn library contains function, namely pkcs1pad2(), wherein converts text numeric values using javascript's charcodeat() function. you'll see conversion code in first while() loop:
function pkcs1pad2(s,n) { if(n < s.length + 11) { // todo: fix utf-8 alert("message long rsa"); return null; } var ba = new array(); var = s.length - 1; while(i >= 0 && n > 0) { var c = s.charcodeat(i--); if(c < 128) { // encode using utf-8 ba[--n] = c; } else if((c > 127) && (c < 2048)) { ba[--n] = (c & 63) | 128; ba[--n] = (c >> 6) | 192; } else { ba[--n] = (c & 63) | 128; ba[--n] = ((c >> 6) & 63) | 128; ba[--n] = (c >> 12) | 224; } } ba[--n] = 0; var rng = new securerandom(); var x = new array(); 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; return new biginteger(ba); } if wish encrypt binary data you'll have modify function converts input in way want it.
below example of pkcs1pad2() modified accept binary data in form of hex string. if use version of pkcs1pad2() can convert cryptojs.lib.wordarray hex , pass hex string rsa.encrypt().
function pkcs1pad2(hexplaintext,n) { if(n < hexplaintext.length/2 + 11) { alert("message long rsa"); return null; } var ba = new array(); var = hexplaintext.length; while(i >= 2 && n > 0) { ba[--n] = parseint(hexplaintext.slice(i-2,i),16); i-=2; } ba[--n] = 0; var rng = new securerandom(); var x = new array(); 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; return new biginteger(ba); } alternatively, modify take wordarray directly , convert array format used jsbn, i'll leave exercise reader.
Comments
Post a Comment