Last active
December 11, 2015 01:58
-
-
Save Yosuke-Kawakami/4527104 to your computer and use it in GitHub Desktop.
PHP と Android のハッシュ化させた文字列を比較させる時の覚書き。【追記】折角なので Javascript 版も追加しておいた
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String sample_conv(String arg_target, String arg_password){ | |
try { | |
Mac mac = Mac.getInstance("HmacSHA256"); | |
SecretKeySpec secret = new SecretKeySpec(arg_password.getBytes("UTF-8"), mac.getAlgorithm()); | |
mac.init(secret); | |
byte[] digest = mac.doFinal(arg_target.getBytes("UTF-8")); | |
String hashed_hex = bin2hex(digest); | |
return Base64.encodeToString(hashed_hex.getBytes("UTF-8"), Base64.DEFAULT).replace("\n", ""); | |
} | |
catch (InvalidKeyException e) { e.printStackTrace();} | |
catch (NoSuchAlgorithmException e) { e.printStackTrace();} | |
catch (UnsupportedEncodingException e) { e.printStackTrace();} | |
return ""; | |
} | |
/** | |
* バイト文字を 16 進数文字列に変換する | |
* | |
* @param data | |
* @author y.k | |
* @version 1.0 | |
*/ | |
public static String bin2hex(byte[] data) { | |
StringBuffer sb = new StringBuffer(); | |
for (byte b : data) { | |
String s = Integer.toHexString(0xff & b); | |
if (s.length() == 1) { sb.append("0"); } | |
sb.append(s); | |
} | |
return sb.toString(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
<!-- | |
/** | |
* ライブラリを利用している | |
* jssha256 : http://point-at-infinity.org/jssha256/ | |
* js-base64 : https://github.com/dankogai/js-base64 | |
*/ | |
function sample_conv(target, password){ | |
var mac_hex = HMAC_SHA256_MAC(password, target); | |
var signature = Base64.encode(mac_hex); | |
return signature; | |
} | |
// --> | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function sample_conv($arg_target, $arg_password){ | |
$myHash = hash_hmac('sha256', $arg_target, $arg_password, false); | |
return base64_encode($myHash); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment