Generate SHA-256 in Kotlin (GS256K)

SHA-256 (Secure Hash Algorithm 256-bit) is a cryptographic hash function algorithm used to generate a unique hash value from a set of input data. This algorithm belongs to the SHA-2 (Secure Hash Algorithm 2) algorithm family designed by the National Security Agency (NSA) and published by the National Institute of Standards and Technology (NIST) in the United States.

Here are the general steps of how SHA-256 works:

1. Message Concatenation (Padding): The input message is converted into a series of fixed-length blocks. The message is then padded to ensure that its length is a multiple of 512 bits (64 bytes). Padding typically involves adding a 1 bit to the end of the message, followed by a number of 0 bits and the original message length.

2. Variable Initialization: The algorithm has a number of internal variables referred to as “hash values” or “state variables.” These variables are set to certain initial values ​​according to the SHA-256 specification.

3. Message Block Processing:

  • The padded message is divided into 512-bit blocks.
  • Each block is processed one by one using cryptographic logic functions.

4. Logical Functions:

  • SHA-256 uses six cryptographic logic functions, involving bit operations such as AND, OR, XOR, and bit rotation.
  • These functions are applied to the message block and internal variables to produce a new hash value.

5. Iteration:

  • The block processing process is repeated a number of times (64 iterations) to produce the final hash value.
  • Each iteration involves complex operations to modify internal variables.

6. Final Result:

  • After all message blocks are processed, the final hash value is taken from an internal variable.
  • This hash value is a unique representation of the input message, and has a length of 256 bits (32 bytes).

SHA-256 is designed to produce hash values ​​that are very difficult to change (resistant to change) and exhibit random properties (unpredictable) making it suitable for use in cryptographic security such as password security, digital signing, and data integrity validation.

Implementation example in Kotlin

Class Hasher {
   fun  hash (): String {
     val bytes = this .toString().toByteArray()
     val md = MessageDigest.getInstance( "SHA-256" )
     val digest = md.digest(bytes)
     return digest.fold( " " , { str, it -> str + "%02x" .format(it) })
  }
}

Post a Comment

Previous Next

نموذج الاتصال