doudaifu6083 2017-03-29 20:17
浏览 338
已采纳

CryptoJS加密Go解密

I have the following Go code

ciphertext := "Zff9c+F3gZu/lsARvPhpMau50KUkMAie4j8MYfb12HMWhkLqZreTk8RPbtRB7RDG3QFw7Y0FXJsCq/EBEAz//XoeSZmqZXoyq2Cx8ZV+/Rw="
decodedText, _ := base64.StdEncoding.DecodeString(ciphertext)
decodedIv, _ := base64.StdEncoding.DecodeString("u9CV7oR2w+IIk8R0hppxaw==")
newCipher, _ := aes.NewCipher([]byte("~NB8CcOL#J!H?|Yr"))
cfbdec := cipher.NewCBCDecrypter(newCipher, decodedIv)
cfbdec.CryptBlocks(decodedText, decodedText)
data, _ := base64.StdEncoding.DecodeString(string(decodedText))
println(string(data))

The output is {"data":{"value":300}, "SEQN":700 , "msg":"IT WORKS!!"

It's encrypted with the following CryptoJS

function encrypt(message, key) {
  let keyHex = CryptoJS.enc.Hex.parse(parseToHex(key))
  let iv = CryptoJS.lib.WordArray.random(128 / 8);
  let wordArray = CryptoJS.enc.Utf8.parse(message);
  let base64 = CryptoJS.enc.Base64.stringify(wordArray);
  let encrypted = CryptoJS.AES.encrypt(base64, keyHex, { iv: iv });
  return {
    cipher: encrypted.ciphertext.toString(CryptoJS.enc.Base64),
    iv: CryptoJS.enc.Base64.stringify(iv),
    length: base64.length,
    size: encrypted.ciphertext.sigBytes,
  }
}

And can be decrypted with

function decrypt(message, key, iv) {
  let ivEX = CryptoJS.enc.Hex.parse(decodeToHex(iv));
  let keyEX = CryptoJS.enc.Hex.parse(parseToHex(key));
  let bytes = CryptoJS.AES.decrypt(message, keyEX , { iv: ivEX});
  let plaintext = bytes.toString(CryptoJS.enc.Base64);
  return decodeToString(decodeToString(plaintext));
}

The output is {"data":{"value":300}, "SEQN":700 , "msg":"IT WORKS!!" } - this is the correct output

Why Go has different output?

  • 写回答

1条回答 默认 最新

  • dongque8332 2017-03-29 21:21
    关注

    Check your errors please. ALWAYS

    illegal base64 data at input byte 75

    https://play.golang.org/p/dRLIT51u4I

    More specifically, the value at byte 75 is 5, which is out of the range of characters available to base64. In ascii, it is the ENQ (enquiry) character. As to why this ends up in your final base64 string is beyond me.

    EDIT: OK found the issue. For whatever reason, the base64 padding character = at the end is being decrypted as 5 consecutive bytes containing the value 5. Here is a playground link that shows it fixed. https://play.golang.org/p/tf3OZ9XG1M

    EDIT: As per matt's comments. I updated the fix function to simply remove all the PKCS7 block padding and use RawStdEncoding for the last base64 decode. This should now be a reasonable fix.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler