golang 與 js 的des加密
1. Abstract</h2>
1. Abstract</h2>
1.1 des好處
- Des加密之后密文比原文長不了多少。
- 加密參數少。沒有iv不用同步比較方便。
1.2 des難度
- 單獨語言的加解密example還是比較多的,但是兩種語言結果能做到一致就比較難了。
- 猜出現亂碼很難,有可能是字符集。
1.3 解決辦法
直接復制我整理好的
2. js加解密及其測試(來源:github)</h2>
2. js加解密及其測試(來源:github)</h2>
引用原文:https://gist.github.com/ufologist/5581486
但是做了一些修改。(CryptoJS.pad.ZeroPadding)
//cryptoJS <script src="./tripledes.js"></script> <script src="./mode-ecb-min.js"></script> <script src="./pad-zeropadding-min.js"></script>
function encryptByDES(message, key) {
var keyHex = CryptoJS.enc.Utf8.parse(key);
var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.ZeroPadding
});
return encrypted.toString();
}
function decryptByDES(ciphertext, key) {
var keyHex = CryptoJS.enc.Utf8.parse(key);
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
}, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.ZeroPadding
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
var message = 't';
var key = '5e8487e6';
var ciphertext = encryptByDES(message, key);
// ciphertext: 8dKft9vkZ4I=
console.info('ciphertext:', ciphertext);
var plaintext = decryptByDES(ciphertext, key);
// plaintext : Message
console.info('plaintext :', plaintext);</pre>
3. golang 加解密及其測試</h2>
引用原文:https://gist.github.com/cuixin/10612934
des.go 文件沒做修改
與js一起使用的例子:key := []byte("5e8487e6")
//解密,reply是從js中收到的加密字符串
fmt.Println("Received back from client: " + reply)
ddd, := base64.StdEncoding.DecodeString(reply)//js加密后的結果是base64的,要轉成byte的。
destext, := DesDecrypt(ddd, key)
fmt.Println("獲取解密結果:", string(destext))//拿到結果
//貼心tip: string->[]byte看這里 []byte("XXX")
//加密,接上面
outs, _ := DesEncrypt(destext, key)
dist := make([]byte, 2048) //開辟存儲空間
base64.StdEncoding.Encode(dist, outs)
fmt.Println("加密送出:", string(dist))</pre>
來自:http://www.philo.top/2015/03/18/golang-js-des/