Skip to content

Commit 73ff642

Browse files
ATL-6924: Add support for encoding functions
This commit adds support to decode hex strings into Sha256Hash bytes
1 parent a8afcd6 commit 73ff642

File tree

1 file changed

+38
-9
lines changed

1 file changed

+38
-9
lines changed

node/src/main/scala/io/iohk/atala/prism/node/crypto/CryptoUtils.scala

+38-9
Original file line numberDiff line numberDiff line change
@@ -38,26 +38,55 @@ object CryptoUtils {
3838

3939
Security.addProvider(provider)
4040

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+
)
4656
}
4757

4858
def bytesToHex(bytes: Vector[Byte]): String = {
4959
bytes.map(byte => f"${byte & 0xff}%02x").mkString
5060
}
5161

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+
)
5483
}
5584

5685
def checkECDSASignature(msg: Array[Byte], sig: Array[Byte], pubKey: SecpPublicKey): Boolean = {
5786
val ecdsaVerify = Signature.getInstance("SHA256withECDSA", provider)
5887
ecdsaVerify.initVerify(pubKey.publicKey)
59-
ecdsaVerify.update(msg.toArray)
60-
ecdsaVerify.verify(sig.toArray)
88+
ecdsaVerify.update(msg)
89+
ecdsaVerify.verify(sig)
6190
}
6291

6392
def unsafeToSecpPublicKeyFromByteCoordinates(x: Array[Byte], y: Array[Byte]): SecpPublicKey = {

0 commit comments

Comments
 (0)