Base64编码/解码问题

时间:2015-05-23 23:26:04

标签: openssl hex base64 ocaml

我有两个函数可以使用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字符串格式化问题吗?

1 个答案:

答案 0 :(得分:2)

openssl每隔64个字符编写带有嵌入换行符的base64文本。这意味着您对echo -n内的decode_base64的输入中包含换行符。这将为您提供"未终止的引用字符串"消息。

无论如何,这是在OCaml中进行base64编码的一种疯狂方式。查看{{3}}