Created
December 6, 2013 10:19
-
-
Save sasaki-shigeo/7821546 to your computer and use it in GitHub Desktop.
Sample code for Message Digest (Secure Hash Function) in Scala
一方向ハッシュ関数のプログラム例
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
import java.security.MessageDigest | |
def hexBytes(bs: Array[Byte]):String = | |
bs.map("%02X".format(_)).mkString(" ") | |
val md2 = MessageDigest.getInstance("MD2") | |
val md5 = MessageDigest.getInstance("MD5") | |
val sha1 = MessageDigest.getInstance("SHA-1") | |
val sha256 = MessageDigest.getInstance("SHA-256") | |
val sha384 = MessageDigest.getInstance("SHA-384") | |
val sha512 = MessageDigest.getInstance("SHA-512") | |
val bytes = "plain text".getBytes | |
md2.update(bytes) | |
md5.update(bytes) | |
sha1.update(bytes) | |
sha256.update(bytes) | |
sha384.update(bytes) | |
sha512.update(bytes) | |
printf("MD2: %s%n", hexBytes(md2.digest)) | |
printf("MD5: %s%n", hexBytes(md5.digest)) | |
printf("SHA-1: %s%n", hexBytes(sha1.digest)) | |
printf("SHA-256: %s%n", hexBytes(sha256.digest)) | |
printf("SHA-384: %s%n", hexBytes(sha384.digest)) | |
printf("SHA-512: %s%n", hexBytes(sha512.digest)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
java.security.MessageDigest の使い方
import
import java.security.MessageDigest
MessageDigest オブジェクトの生成
md = MessageDigest.getInstance(アルゴリズム名)
1バイト送り込む
md.update(b: Byte)
バイト列を送り込む
md.update(bs: Array[Byte])
ハッシュ値を得る (戻り値の型は Array[Byte])
md.digest