Base64 encode/decode 问题

Base64 encode/decode issue

我有两个函数可以使用 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 函数时,我收到错误消息。我看不出我做错了什么,但我认为问题一定出在解码函数中,因为我一直在许多其他 API 接口中使用编码函数,没有问题。

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

openssl 正在编写每 64 个字符嵌入换行符的 base64 文本。这意味着您在 decode_base64 中对 echo -n 的输入包含换行符。这会给您 "Unterminated quoted string" 消息。

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