【问题标题】:Base64 encode/decode issueBase64 编码/解码问题
【发布时间】:2015-05-23 23:26:04
【问题描述】:

我有两个函数可以使用 openssl 与 base64 相互转换:

 (* base64 encode *)
 let encode_base64 msg =
   let open_ssl_arg = "echo -n '" ^ msg ^ "' | openssl enc -base64" in
   let ic = Unix.open_process_in open_ssl_arg in
   let rec output s =
     try let new_line = input_line ic in output (s ^ new_line);
     with End_of_file -> s
   in
  Unix.close_process_in |> fun _ -> ();
  output ""

(* base64 decode *)
let decode_base64 msg =
  let open_ssl_arg = "echo -n '" ^ msg ^ "' | base64 -d" in
  let ic = Unix.open_process_in open_ssl_arg in
  let rec output s =
    try let new_line = input_line ic in output (s ^ new_line);
    with End_of_file -> s
  in
  Unix.close_process_in |> fun _ -> ();
  output ""

这些似乎工作正常。我可以用类似的东西来测试它们:

 # decode_base64 @@ encode_base64 "HelloWorld";;
 - : string = "HelloWorld" 

作为我正在构建的 API 接口的一部分,我需要能够对密钥进行 base64 解码。

当我使用 API 提供的密钥尝试相同的测试时,我收到以下消息:

 encode_base64 @@ decode_base64 secret_key;;
 /bin/sh: 1: Syntax error: Unterminated quoted string                            
 - : string = ""

我可以很好地解码密钥,但是当我将解码的密钥字符串放回 encode_base64 函数时,我收到了错误。我看不出我做错了什么,但我认为问题一定出在 decode 函数中,因为我在许多其他 API 接口中一直使用 encode 函数没有问题。

我也知道我的密钥不是问题,因为我可以使用相同的密钥在 python 中执行所有功能。这可能是 Oct vs Hex 字符串格式问题吗?

【问题讨论】:

    标签: openssl hex base64 ocaml


    【解决方案1】:

    openssl 正在编写 base64 文本,每 64 个字符嵌入换行符。这意味着您在decode_base64 内对echo -n 的输入包含换行符。这会给你“未终止的引用字符串”消息。

    无论如何,这是在 OCaml 中进行 base64 编码的一种疯狂方式。查看https://github.com/mirage/ocaml-base64

    【讨论】:

    • 我不知道这个库,谢谢你的信息。
    猜你喜欢
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2011-09-22
    • 2016-04-01
    • 2015-07-21
    • 2010-12-29
    相关资源
    最近更新 更多