暗号化と復号化のとても簡単なサンプル
備忘録的に書いておきます。
(つまり、つまずいた)
・文字列をUint8Array と言う数値配列に変換
・その数値を(パスワードを使うなどして)ある規則に則って変換
これが暗号化された文章
・暗号化された文章を、(パスワードを使うなどして)規則に則ってUint8Arrayに変換
・Uint8Array を文字列に変換
これが復号化された文章
---------------------------------------------------------------
//Uint8Array と文字列の変換のためのAPI定義
const encoder = new TextEncoder()
const decoder = new TextDecoder()
//元の文章
const Bunsyo="これが元の文章";
//Uint8Array に変換
const Uint8Bunsyo=encoder.encode(Bunsyo);
//例えば各数値に256を加えて暗号化処理とする
//Uint8Array の最大値は256なので普通の配列に変換しておく
const Uint8plus256=Array.from(Uint8Bunsyo);
const plus256=Uint8plus256.map((x,index)=>{
return x+256;
})
//この例の暗号文章は以下のようになる
//483,385,403,483,386,396,483,385,396,485,389,387,483,385,430,486,406,391,487,427,416
//復号化
let minus256 =plus256.map((x,index)=>{
return x-256;
})
let Uint8minus=new Uint8Array(minus256);
let fukugou=decoder.decode(Uint8minus)
this.FatalErrorText+="\n\n復号文章\n";
this.FatalErrorText+=fukugou;
//この結果の復号文章は以下のようになる
//これが元の文章
---------------------------------------------------------------
注:
配列のmapで(x,index)とindexを定義しているが、今回は使っていない(省略可能)
複雑な処理をするなら便利かもしれない
なおthis.FatalErrorTextは単に変数の使いまわしです。
追記:
よく考えて見れば、Uint8Arrayから普通の配列に変更する必要は無いです。ちょっと違う例ですが
const testplus=Uint8Bunsyo.map((x,index)=>((x+index)%256));
this.FatalErrorText="\n\n暗号文章\n";
this.FatalErrorText+=JSON.stringify(testplus);
const testminus=testplus.map((x,index)=>(x-index+256)%256);
this.FatalErrorText+="\n\n文章\n";
this.FatalErrorText+=decoder.decode(testminus);
こんな感じで256の剰余を取れば、問題ないですね。
追記:
Uint8ArrayとかUint16ArrayやUint32Arrayの変換例(同じアドレスを見ているので変換と言うより表示)
なおUint8Arrayの要素が、それぞれ2の倍数・4の倍数でないと実行時エラーが出ます。
(例:Error: buffer length for Uint16Array should be a multiple of 2)
let n8=new Uint8Array([12,255,37,255])
console.log(n8)
let n16=new Uint16Array(n8.buffer)
console.log(n16)
let n32=new Uint32Array(n8.buffer)
console.log(n32)
let nn8=new Uint8Array(n32.buffer)
console.log(nn8)
//実行結果
//> Uint8Array [12, 255, 37, 255]
//> Uint16Array [65292, 65317]
//> Uint32Array [4280680204]
//> Uint8Array [12, 255, 37, 255]