What You'll Learn

Here are the objectives of this lab:

Advanced Encryption Standard (AES) is a highly trusted encryption algorithm used to secure data by converting it into an unreadable format without the proper key. Developed by the National Institute of Standards and Technology (NIST), AES encryption uses various key lengths (128, 192, or 256 bits) to provide strong protection against unauthorized access. This data security measure is efficient and widely implemented in securing internet communication, protecting sensitive data, and encrypting files. AES, a cornerstone of modern cryptography, is recognized globally for its ability to keep information safe from cyber threats.

import java.security.MessageDigest
import kotlin.text.Charsets.UTF_8
import javax.crypto.spec.SecretKeySpec
import javax.crypto.spec.IvParameterSpec
import javax.crypto.SecretKey
import javax.crypto.Cipher
import kotlin.io.encoding.Base64

fun ByteArray.toHex() = joinToString(separator = "") { byte -> "%02x".format(byte) }

fun getFirstNChars(str: String, n:Int) = str.substring(0,n)
fun hashStrSha256(str: String): String{
    val algorithm = "SHA-256"
    val hashedString = MessageDigest.getInstance(algorithm).digest(str.toByteArray(UTF_8))
    return hashedString.toHex();
}
fun generateAESKey(seed: String): SecretKeySpec {
  val first32Chars = getFirstNChars(seed,32)
  val secretKey = SecretKeySpec(first32Chars.toByteArray(), "AES")
  return secretKey
}
fun generateIV(seed: String): IvParameterSpec {
    val first16Chars = getFirstNChars(seed, 16)
    return IvParameterSpec(first16Chars.toByteArray())
}
fun encryptMessage(plaintext: String, aesKey:SecretKey, aesIv: IvParameterSpec):String{
    val plainTextByteArr = plaintext.toByteArray()

    val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
    cipher.init(Cipher.ENCRYPT_MODE, aesKey, aesIv)

    val encrypt = cipher.doFinal(plainTextByteArr)
    return Base64.Default.encode(encrypt)
}
fun decryptMessage(encryptedText: String, aesKey:SecretKey, aesIv: IvParameterSpec):String{
    val textToDecrypt = Base64.Default.decode(encryptedText)

    val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
    
    cipher.init(Cipher.DECRYPT_MODE, aesKey,aesIv)

    val decrypt = cipher.doFinal(textToDecrypt)
    return String(decrypt)

}

fun main(){
    val seedPlaintext = "TheWorldSeedKirito"
    val strongSeed = hashStrSha256(seedPlaintext)
    val aesKey = generateAESKey(strongSeed)
    val aesIV = generateIV(strongSeed)

    val plaintextMessage = "Hello world!"
    
    println(plaintextMessage)
    
    val cyphertext = encryptMessage(plaintextMessage, aesKey, aesIV)
    val decryptedCypherText = decryptMessage(cyphertext, aesKey, aesIV)

    println(cyphertext)
    println(decryptedCypherText)

}