|
Play Framework/Scala example source code file (Codecs.scala)
The Codecs.scala Play Framework example source code
/*
* Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
*/
package play.api.libs
/**
* Utilities for Codecs operations.
*/
object Codecs {
/**
* Computes the SHA-1 digest for a byte array.
*
* @param bytes the data to hash
* @return the SHA-1 digest, encoded as a hex string
*/
def sha1(bytes: Array[Byte]): String = {
import java.security.MessageDigest
val digest = MessageDigest.getInstance("SHA-1")
digest.reset()
digest.update(bytes)
digest.digest().map(0xFF & _).map { "%02x".format(_) }.foldLeft("") { _ + _ }
}
/**
* Computes the MD5 digest for a byte array.
*
* @param bytes the data to hash
* @return the MD5 digest, encoded as a hex string
*/
def md5(bytes: Array[Byte]): String = {
import java.security.MessageDigest
val digest = MessageDigest.getInstance("MD5")
digest.reset()
digest.update(bytes)
digest.digest().map(0xFF & _).map { "%02x".format(_) }.foldLeft("") { _ + _ }
}
/**
* Compute the SHA-1 digest for a `String`.
*
* @param text the text to hash
* @return the SHA-1 digest, encoded as a hex string
*/
def sha1(text: String): String = sha1(text.getBytes)
// --
private val hexChars = Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')
/**
* Converts a byte array into an array of characters that denotes a hexadecimal representation.
*/
def toHex(array: Array[Byte]): Array[Char] = {
val result = new Array[Char](array.length * 2)
for (i <- 0 until array.length) {
val b = array(i) & 0xff
result(2 * i) = hexChars(b >> 4)
result(2 * i + 1) = hexChars(b & 0xf)
}
result
}
/**
* Converts a byte array into a `String` that denotes a hexadecimal representation.
*/
def toHexString(array: Array[Byte]): String = {
new String(toHex(array))
}
/**
* Transform an hexadecimal String to a byte array.
*/
def hexStringToByte(hexString: String): Array[Byte] = {
import org.apache.commons.codec.binary.Hex;
Hex.decodeHex(hexString.toCharArray());
}
}
Other Play Framework source code examplesHere is a short list of links related to this Play Framework Codecs.scala source code file: |
| ... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.