ScrambledKeyPair.ts
1 import * as forge from 'node-forge' 2 3 const rsa = forge.pki.rsa 4 5 function scrambleModulus( values: Array<number> ) : Buffer { 6 let scrambledMod = Buffer.from( values ) 7 8 if ( ( scrambledMod.length === 0x81 ) && ( scrambledMod[ 0 ] === 0x00 ) ) { 9 scrambledMod = scrambledMod.subarray( 1 ) 10 } 11 // step 1 : 0x4d-0x50 <-> 0x00-0x04 12 for ( let i = 0; i < 4; i++ ) { 13 let temp = scrambledMod[ i ] 14 scrambledMod[ i ] = scrambledMod[ 0x4d + i ] 15 scrambledMod[ 0x4d + i ] = temp 16 } 17 // step 2 : xor first 0x40 bytes with last 0x40 bytes 18 for ( let i = 0; i < 0x40; i++ ) { 19 scrambledMod[ i ] = scrambledMod[ i ] ^ scrambledMod[ 0x40 + i ] 20 } 21 // step 3 : xor bytes 0x0d-0x10 with bytes 0x34-0x38 22 for ( let i = 0; i < 4; i++ ) { 23 scrambledMod[ 0x0d + i ] = scrambledMod[ 0x0d + i ] ^ scrambledMod[ 0x34 + i ] 24 } 25 // step 4 : xor last 0x40 bytes with first 0x40 bytes 26 for ( let i = 0; i < 0x40; i++ ) { 27 scrambledMod[ 0x40 + i ] = scrambledMod[ 0x40 + i ] ^ scrambledMod[ i ] 28 } 29 30 return scrambledMod 31 } 32 33 export interface L2KeyPair { 34 value: any 35 modulus: Buffer 36 } 37 38 39 export function createKeyPair() :L2KeyPair { 40 let value = rsa.generateKeyPair( { bits: 1024, e: 0x10001 } ) 41 return { 42 value, 43 modulus: scrambleModulus( value.publicKey.n.toByteArray() ) 44 } 45 }