From 436b5f108cd7f0f3a0c0bfb9f7137b4a2ec3b8a8 Mon Sep 17 00:00:00 2001 From: Leonardo Colman Lopes Date: Thu, 21 Dec 2023 22:41:39 -0300 Subject: [PATCH] [KTLN-789] Add Samples (#725) * [KTLN-789] Add Samples * [KTLN-789] Add Samples * [KTLN-789] Add Samples --- .../kotlin/com/baeldung/md5/Md5UnitTest.kt | 40 +++++++++++++++++++ .../src/test/resources/test_md5.txt | 1 + 2 files changed, 41 insertions(+) create mode 100644 core-kotlin-modules/core-kotlin-9/src/test/kotlin/com/baeldung/md5/Md5UnitTest.kt create mode 100644 core-kotlin-modules/core-kotlin-9/src/test/resources/test_md5.txt diff --git a/core-kotlin-modules/core-kotlin-9/src/test/kotlin/com/baeldung/md5/Md5UnitTest.kt b/core-kotlin-modules/core-kotlin-9/src/test/kotlin/com/baeldung/md5/Md5UnitTest.kt new file mode 100644 index 000000000..aa5a2c973 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-9/src/test/kotlin/com/baeldung/md5/Md5UnitTest.kt @@ -0,0 +1,40 @@ +package com.baeldung.md5 + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import java.io.File +import java.security.MessageDigest + +class Md5UnitTest { + @Test + fun `Calling extension md5 should return a md5 hash`() { + val stringToBeHashed = "Hello, Baeldung!" + val expectedHash = "6469a4ea9e2753755f5120beb51587f8" + val calculatedHash = stringToBeHashed.md5() + + assertEquals(expectedHash, calculatedHash) + } + + @Test + fun `Calling extension md5 on a file should return a md5 hash`() { + val fileToBeHashed = File("src/test/resources/test_md5.txt") + val expectedHash = "ef948f943cdba8514ed5aab7592a904d" + val calculatedHash = fileToBeHashed.md5() + + assertEquals(expectedHash, calculatedHash) + } +} + +@OptIn(ExperimentalStdlibApi::class) +fun String.md5(): String { + val md = MessageDigest.getInstance("MD5") + val digest = md.digest(this.toByteArray()) + return digest.toHexString() +} + +@OptIn(ExperimentalStdlibApi::class) +fun File.md5(): String { + val md = MessageDigest.getInstance("MD5") + val digest = md.digest(this.readBytes()) + return digest.toHexString() +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-9/src/test/resources/test_md5.txt b/core-kotlin-modules/core-kotlin-9/src/test/resources/test_md5.txt new file mode 100644 index 000000000..8271922f9 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-9/src/test/resources/test_md5.txt @@ -0,0 +1 @@ +Hello, Baeldung! I'm a file! \ No newline at end of file