2015-05-23 116 views
0

我有兩個功能轉換使用OpenSSL的,並從BASE64:的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接口中使用編碼函數而沒有任何問題。

而且我知道我的祕密密鑰是沒有問題的,因爲我可以僅執行與相同的密鑰蟒蛇精的所有功能。這可能是一個十月與十六進制字符串格式問題?

回答

2

OpenSSL是寫每64個字符嵌入換行符以base64文本。這意味着,你的輸入echo -ndecode_base64中有換行。這給你提供了「Unterminated quoted string」消息。

無論如何,這是一種在OCaml中做base64編碼的瘋狂方式。退房https://github.com/mirage/ocaml-base64

+0

我不知道這個庫的,感謝信息。 – Thomas