OSDN Git Service

hmac-sha256 function.
authorvisor <visor@users.sourceforge.jp>
Mon, 13 May 2013 15:06:34 +0000 (00:06 +0900)
committervisor <visor@users.sourceforge.jp>
Mon, 13 May 2013 15:06:34 +0000 (00:06 +0900)
modules/ml-security.cc
modules/ml-security.h

index 28beddb..da0d157 100644 (file)
@@ -67,6 +67,57 @@ MNode*  ml_hmac_sha1 (MNode* cell, MlEnv* mlenv) {
 }
 
 /*DOC:
+===hmac-sha256===
+ (hmac-sha256 KEY_STRING TEXT [#hex] [#base64]) => STRING
+
+*/
+//#AFUNC       hmac-sha256     ml_hmac_sha256
+//#WIKIFUNC    hmac-sha256
+MNode*  ml_hmac_sha256 (MNode* cell, MlEnv* mlenv) {
+    MNode*  arg = cell->cdr ();
+    ustring  key;
+    ustring  text;
+    enum {
+       ENC_HEX,
+       ENC_BASE64,
+    }  encode = ENC_HEX;
+    ustring  ans;
+    unsigned char  md[EVP_MAX_MD_SIZE];
+    unsigned int  md_len;
+    std::vector<MNode*>  params;
+    std::vector<MNode*>  keywords;
+    static paramList  kwlist[] = {
+       {CharConst ("hex"), true},
+       {CharConst ("base64"), true},
+       {NULL, 0, 0}
+    };
+
+    setParams (arg, 2, &params, kwlist, &keywords, NULL);
+    key = eval_str (params[0], mlenv);
+    text = eval_str (params[1], mlenv);
+    if (keywords[0] && eval_bool (keywords[0], mlenv))
+       encode = ENC_HEX;
+    if (keywords[1] && eval_bool (keywords[1], mlenv))
+       encode = ENC_BASE64;
+
+    HMAC (EVP_sha256 (), key.c_str (), key.length (), uchar_type (text.c_str ()), text.length (), md, &md_len);
+
+    ans.assign (char_type (md), md_len);
+    switch (encode) {
+    case ENC_HEX:
+       ans = hexEncode (ans);
+       break;
+    case ENC_BASE64:
+       ans = base64Encode (ans.begin (), ans.end ());
+       break;
+    default:
+       assert (0);
+    }
+
+    return newMNode_str (new ustring (ans));
+}
+
+/*DOC:
 ===md5-string===
  (md5-string TEXT [#hex | #base64 | :hex BOOL | :base64 BOOL]) -> STRING
 
index 1c920b2..57bab2b 100644 (file)
@@ -8,6 +8,7 @@ class  MNode;
 class  MlEnv;
 
 MNode*  ml_hmac_sha1 (MNode* cell, MlEnv* mlenv);
+MNode*  ml_hmac_sha256 (MNode* cell, MlEnv* mlenv);
 MNode*  ml_md5_string (MNode* cell, MlEnv* mlenv);
 MNode*  ml_md5_file (MNode* cell, MlEnv* mlenv);