@blog.justoneplanet.info

日々勉強

HMAC-MD5を計算する

■PHP

hash_hmac('md5', $str, 'key');

■Python

import hmac
from hashlib import sha1
from hashlib import md5
hmac.new("key", "value", md5).hexdigest()
hmac.new("key", "value", sha1).hexdigest()

■Android

public class HmacMD5 {
private static final String ALGORISM = “HmacMD5”;
private static final String S = “key”;
public static String get(String str) {
SecretKeySpec secretKeySpec = new SecretKeySpec(S.getBytes(), ALGORISM);
try {
Mac mac = Mac.getInstance(ALGORISM);
mac.init(secretKeySpec);
byte[] result = mac.doFinal(str.getBytes());
return byteToString(result);
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (InvalidKeyException e) {
e.printStackTrace();
}
return “”;
}

private static String byteToString(byte [] b) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < b.length; i++) { int d = b[i]; d += (d < 0)? 256 : 0; if (d < 16) { buffer.append("0"); } buffer.append(Integer.toString(d, 16)); } return buffer.toString(); } } [/sourcecode]

■iOS

日本語入力に対応するためにstackoverflowから持ってきたコードに少々手を入れた。

+ (NSString *)HMACMD5WithKey:(NSString *)data
{
const char *cKey = [@”key” cStringUsingEncoding:NSUTF8StringEncoding];
const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];
const unsigned int blockSize = 64;
char ipad[blockSize];
char opad[blockSize];
char keypad[blockSize];

unsigned int keyLen = strlen(cKey);
CC_MD5_CTX ctxt;
if (keyLen > blockSize) {
CC_MD5_Init(&ctxt);
CC_MD5_Update(&ctxt, cKey, keyLen);
CC_MD5_Final((unsigned char *)keypad, &ctxt);
keyLen = CC_MD5_DIGEST_LENGTH;
}
else {
memcpy(keypad, cKey, keyLen);
}

memset(ipad, 0x36, blockSize);
memset(opad, 0x5c, blockSize);

int i;
for (i = 0; i < keyLen; i++) { ipad[i] ^= keypad[i]; opad[i] ^= keypad[i]; } CC_MD5_Init(&ctxt); CC_MD5_Update(&ctxt, ipad, blockSize); CC_MD5_Update(&ctxt, cData, strlen(cData)); unsigned char md5[CC_MD5_DIGEST_LENGTH]; CC_MD5_Final(md5, &ctxt); CC_MD5_Init(&ctxt); CC_MD5_Update(&ctxt, opad, blockSize); CC_MD5_Update(&ctxt, md5, CC_MD5_DIGEST_LENGTH); CC_MD5_Final(md5, &ctxt); const unsigned int hex_len = CC_MD5_DIGEST_LENGTH*2+2; char hex[hex_len]; for(i = 0; i < CC_MD5_DIGEST_LENGTH; i++) { snprintf(&hex[i*2], hex_len-i*2, "%02x", md5[i]); } NSData *HMAC = [[NSData alloc] initWithBytes:hex length:strlen(hex)]; NSString *hash = [[[NSString alloc] initWithData:HMAC encoding:NSUTF8StringEncoding] autorelease]; [HMAC release]; return hash; } [/sourcecode]

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment