■ はじめに
http://blogs.yahoo.co.jp/dk521123/33829893.html
などで、byte配列を16進数文字列 に変換する必要があり
以前は、以下のように独自にしていたが、簡単に実装できるのでメモ。
以前の実装: byte配列⇒16進数文字列 の変換
byte[] hashValues = messageDigest.digest();
StringBuffer stringBuffer = new StringBuffer();
for (byte hashValue : hashValues) {
stringBuffer.append(String.format("%02x", hashValue));
}
returnValue = stringBuffer.toString();
修正後
returnValue = DatatypeConverter.printHexBinary(hashValues);
■ 注意:「Apache Commons Codec の Hex クラス」と「DatatypeConverter クラス」の違い
実は、このことが今回のブログの本当の目的
はじめに
* 大した事じゃないかもしれないが、Hex.encodeHexString()で実装されていたコードを
DatatypeConverter.printHexBinary() で置き換えたのだが、単体試験が通らなかった。
結論
* 結果が、小文字・大文字の違いがある
=> もし、移行する際は気を付けて下さい
サンプル
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.binary.Hex;
public class Main {
public static void main(String[] args) {
System.out.println("Result1 : " + Hex.encodeHexString("あいう".getBytes()));
System.out.println("Result2 : " + DatatypeConverter.printHexBinary("あいう".getBytes()));
}
}
出力結果
結果が、小文字・大文字の違いがある
Result1 : 82a082a282a4
Result2 : 82A082A282A4