@@ -38,26 +38,55 @@ object CryptoUtils {
38
38
39
39
Security .addProvider(provider)
40
40
41
- def hash (bArray : Array [Byte ]): Vector [Byte ] = {
42
- MessageDigest
43
- .getInstance(" SHA-256" )
44
- .digest(bArray)
45
- .toVector
41
+ trait Sha256Hash {
42
+ def bytes : Vector [Byte ]
43
+ }
44
+
45
+ private [crypto] case class Sha256HashImpl (bytes : Vector [Byte ]) extends Sha256Hash {
46
+ require(bytes.size == 32 )
47
+ }
48
+
49
+ def sha256Hash (bArray : Array [Byte ]): Sha256Hash = {
50
+ Sha256HashImpl (
51
+ MessageDigest
52
+ .getInstance(" SHA-256" )
53
+ .digest(bArray)
54
+ .toVector
55
+ )
46
56
}
47
57
48
58
def bytesToHex (bytes : Vector [Byte ]): String = {
49
59
bytes.map(byte => f " ${byte & 0xff }%02x " ).mkString
50
60
}
51
61
52
- def hexedHash (bArray : Array [Byte ]): String = {
53
- bytesToHex(hash(bArray))
62
+ def hexToBytes (hex : String ): Vector [Byte ] = {
63
+ val HEX_ARRAY = " 0123456789abcdef" .toCharArray
64
+ for {
65
+ pair <- hex.grouped(2 ).toVector
66
+ firstIndex = HEX_ARRAY .indexOf(pair(0 ))
67
+ secondIndex = HEX_ARRAY .indexOf(pair(1 ))
68
+ octet = firstIndex << 4 | secondIndex
69
+ } yield octet.toByte
70
+ }
71
+
72
+ def hexedHash (hash : Sha256Hash ): String = {
73
+ bytesToHex(hash.bytes)
74
+ }
75
+
76
+ def fromHex (hexedBytes : String ): Sha256Hash = {
77
+ val HEX_STRING_RE = " ^[0-9a-fA-F]{64}$" .r
78
+ if (HEX_STRING_RE .matches(hexedBytes)) Sha256HashImpl (hexToBytes(hexedBytes))
79
+ else
80
+ throw new IllegalArgumentException (
81
+ " The given hex string doesn't correspond to a valid SHA-256 hash encoded as string"
82
+ )
54
83
}
55
84
56
85
def checkECDSASignature (msg : Array [Byte ], sig : Array [Byte ], pubKey : SecpPublicKey ): Boolean = {
57
86
val ecdsaVerify = Signature .getInstance(" SHA256withECDSA" , provider)
58
87
ecdsaVerify.initVerify(pubKey.publicKey)
59
- ecdsaVerify.update(msg.toArray )
60
- ecdsaVerify.verify(sig.toArray )
88
+ ecdsaVerify.update(msg)
89
+ ecdsaVerify.verify(sig)
61
90
}
62
91
63
92
def unsafeToSecpPublicKeyFromByteCoordinates (x : Array [Byte ], y : Array [Byte ]): SecpPublicKey = {
0 commit comments