<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>security Archives - Codersee blog- Kotlin on the backend</title>
	<atom:link href="https://blog.codersee.com/tag/security/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Kotlin &#38; Backend Tutorials - Learn Through Practice.</description>
	<lastBuildDate>Wed, 16 Apr 2025 04:49:52 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://blog.codersee.com/wp-content/uploads/2025/04/cropped-codersee_logo_circle_2-32x32.png</url>
	<title>security Archives - Codersee blog- Kotlin on the backend</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Kotlin PBKDF2 Secure Password Hashing</title>
		<link>https://blog.codersee.com/kotlin-pbkdf2-secure-password-hashing/</link>
					<comments>https://blog.codersee.com/kotlin-pbkdf2-secure-password-hashing/#comments</comments>
		
		<dc:creator><![CDATA[Piotr]]></dc:creator>
		<pubDate>Tue, 10 Jan 2023 07:45:47 +0000</pubDate>
				<category><![CDATA[Kotlin]]></category>
		<category><![CDATA[security]]></category>
		<guid isPermaLink="false">https://codersee.com/?p=5504212</guid>

					<description><![CDATA[<p>In this article, we will learn a bit more about Kotlin password hashing, PBKDF2, and how to write a Kotlin code with PBKDF2 in practice.</p>
<p>The post <a href="https://blog.codersee.com/kotlin-pbkdf2-secure-password-hashing/">Kotlin PBKDF2 Secure Password Hashing</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Hello and welcome to the article about <strong>Kotlin password hashing with PBKDF2</strong> (to be even more specific- with <strong>PBKDF2WithHmacSHA512</strong>).</p>
<p>In this hands-on guide, we will:</p>
<ul>
<li>learn why password hashing is important,</li>
<li>discover a couple of definitions every programmer should be aware of,</li>
<li>and finally- how to hash a password with Kotlin and PBKDF2.</li>
</ul>
<h2>What Is Password Hashing and Is It Important?</h2>
<p>Well, <strong>password hashing</strong> is the process of taking a password and applying a mathematical function (the hash function) to it to produce <strong>a fixed-size string of characters-</strong> the <em>hash value</em> (also known as <em>digest</em>).</p>
<p>&nbsp;</p>
<p><img fetchpriority="high" decoding="async" class="aligncenter wp-image-5504213" src="http://blog.codersee.com/wp-content/uploads/2023/01/kotlin_password_hashing_function_process_infographic.png" alt="Infographic presents example Kotlin password hashing function process." width="800" height="600" srcset="https://blog.codersee.com/wp-content/uploads/2023/01/kotlin_password_hashing_function_process_infographic.png 1024w, https://blog.codersee.com/wp-content/uploads/2023/01/kotlin_password_hashing_function_process_infographic-300x225.png 300w, https://blog.codersee.com/wp-content/uploads/2023/01/kotlin_password_hashing_function_process_infographic-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" /></p>
<p>It&#8217;s worth mentioning, that <strong>it is a one-way operation</strong>. We simply can&#8217;t reverse the process and obtain the key from a hash value. So even if attackers gain access to the hashed password in our database, obtaining the original password is difficult.</p>
<p>But difficult, doesn&#8217;t mean impossible. Although the process can&#8217;t be reversed, attackers can try to crack the password using different combinations of characters and computing the hash value for each combination. And because of that, password hashing algorithms are designed to be computationally expensive, meaning that it takes a long time to compute the hash value for a given password.</p>
<p>So, given these points, we can clearly see that <strong>password hashing is important not only when working with Kotlin</strong>.</p>
<h2>What Does Salt Mean?</h2>
<p>Before we dive into the Kotlin password hashing with pbkdf2, let&#8217;s learn more about <strong>salt</strong>.</p>
<p><strong>Salt</strong> is a random value that is generated and added to the input data before it is hashed. Thanks to that, the<strong> resulting hash will be different even if the original passwords are the same</strong>, making it even harder to crack the hashed passwords using precomputed hash tables (also known as <strong>rainbow tables</strong>).</p>
<p>&nbsp;</p>
<p><img decoding="async" class="aligncenter wp-image-5504214" src="http://blog.codersee.com/wp-content/uploads/2023/01/kotlin_password_hashing_function_process_with_salt_infographic.png" alt="Infographic shows how password hashing function works with salt." width="800" height="600" srcset="https://blog.codersee.com/wp-content/uploads/2023/01/kotlin_password_hashing_function_process_with_salt_infographic.png 1024w, https://blog.codersee.com/wp-content/uploads/2023/01/kotlin_password_hashing_function_process_with_salt_infographic-300x225.png 300w, https://blog.codersee.com/wp-content/uploads/2023/01/kotlin_password_hashing_function_process_with_salt_infographic-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" /></p>
<h2>Kotlin / Java Password Hashing Algorithms</h2>
<p>And as the last thing before the practice part, let&#8217;s take a look at a couple of password hashing algorithms, which we can use when working with Kotlin:</p>
<ul>
<li><strong>MD5 (Message Digest Algorithm 5)</strong>, which produces a 128-bit hash value. Nevertheless, it&#8217;s vulnerable to collision attacks and should not be used for password hashing or other sensitive applications.</li>
<li><strong>SHA-512 (Secure Hash Algorithm 512-bit)</strong>, which produces a 512-bit hash value. Technically, it is considered a secure option, but we have better alternatives.</li>
<li><strong>BCrypt</strong>&#8211; a password hashing function based on the Blowfish cipher and including salt to protect against dictionary attacks.</li>
<li><strong>SCrypt</strong>&#8211; a key derivation function designed for GPU cracking attacks. It uses a large amount of memory, making it more expensive to crack.</li>
<li><strong>PBKDF2 (Password-Based Key Derivation Function 2)</strong>, which is also a key derivation function. It is designed to be resistant to dictionary attacks and uses salt and iterative hashing to increase the cost of attacks.</li>
</ul>
<p><a href="https://codersee.com/newsletter/"><img decoding="async" class="aligncenter wp-image-3002956 size-large" src="http://blog.codersee.com/wp-content/uploads/2022/05/join_newsletter-1024x576.png" alt="Image shows two ebooks people can get for free after joining newsletter" width="800" height="419" /></a></p>
<h2>Kotlin With PBKDF2 (<strong>PBKDF2WithHmacSHA512</strong>) In Practice</h2>
<p>So, with all of that being said, we can finally start the coding part. As I mentioned in the beginning, we will see how to hash passwords in Kotlin with <strong>PBKDF2WithHmacSHA512</strong>.</p>
<p>Don&#8217;t worry about this monster- it&#8217;s a name of an algorithm, which we will use when requesting an instance of <em>SecretKeyFactory</em>. Without going into much detail here, our little monster will generate a <strong>512 bits hash value</strong>. (And if you&#8217;re interested in a more detailed answer, then check out <a href="https://stackoverflow.com/questions/19348501/pbkdf2withhmacsha512-vs-pbkdf2withhmacsha1" target="_blank" rel="noopener">this StackOverflow topic</a>).</p>
<h3>Random Salt</h3>
<p>Firstly, let&#8217;s implement a function responsible for generating random salt:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="kotlin">fun generateRandomSalt(): ByteArray {
  val random = SecureRandom()
  val salt = ByteArray(16)
  random.nextBytes(salt)

  return salt
}
</pre>
<p>16-byte salt will be enough. Whatsoever, we create a <em>SecureRandom</em> instance using the default constructor.</p>
<p>But, if we would like to pick a specific algorithm, then we can use the <span style="white-space: pre-wrap;"><em>getInstance</em> method instead: </span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="kotlin"> SecureRandom.getInstance("PKCS11")
</pre>
<p>We can find the list of all supported algorithms <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/security/standard-names.html#securerandom-number-generation-algorithms" target="_blank" rel="noopener">right here</a>.</p>
<p>Lastly, if we would like to convert the <span style="white-space: pre-wrap;">ByteArray to a hex String, we can use the <em>formatHex</em>:</span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="kotlin">private fun ByteArray.toHexString(): String =
  HexFormat.of().formatHex(this)

// so that later, we can simply run:
salt.toHexString()
</pre>
<h3>Generate Hash</h3>
<p>As the last thing in our Kotlin password hashing with PBKDF2, let&#8217;s implement the <em>generateHash</em>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="kotlin">private const val ALGORITHM = "PBKDF2WithHmacSHA512"
private const val ITERATIONS = 120_000
private const val KEY_LENGTH = 256
private const val SECRET = "SomeRandomSecret"

fun generateHash(password: String, salt: String): String {
  val combinedSalt = "$salt$SECRET".toByteArray()

  val factory: SecretKeyFactory = SecretKeyFactory.getInstance(ALGORITHM)
  val spec: KeySpec = PBEKeySpec(password.toCharArray(), combinedSalt, ITERATIONS, KEY_LENGTH)
  val key: SecretKey = factory.generateSecret(spec)
  val hash: ByteArray = key.encoded

  return hash.toHexString()
}
</pre>
<p>As we can see in the first line of our function, we combine the <em>salt</em> with an additional <em>SECRET</em> value. Oftentimes, the salt value is generated for each user in our system, which means that we have to persist it in the database, as well.  So, in case our database data are leaked, we can reduce the risk of password cracking through this additional step.</p>
<blockquote><p>For simplicity, the secret value is stored as a constant, but in a real-life scenario, we&#8217;d rather pass it as an environment variable</p></blockquote>
<p>In the following lines, we define a <em>SecretKeyFactory</em> instance and a <em>KeySpec </em>with the desired password, salt, iterations and key length values.</p>
<h3>Recommended Iterations And Key Length</h3>
<p>When it comes to the number of iterations, in 2021 OWASP recommended <strong>120,000 iterations for PBKDF2-HMAC-SHA512</strong>. The key length is equivalent to the chance for a hash collision, so it&#8217;s good for it to be <strong>at least 128 bits</strong>.</p>
<h2>Kotlin Password Hashing With PBKDF2 Summary</h2>
<p>And that would be all for this article covering <strong>Kotlin password hashing with the PBKDF2 topic</strong>.</p>
<p>If you enjoyed this content, then you might also be interested in one of the following posts:</p>
<ul>
<li><a href="https://blog.codersee.com/a-guide-to-mockk-library/"> A Guide to MockK: a Mocking Library for Kotlin</a></li>
<li><a href="https://blog.codersee.com/sring-boot-kotlin-apache-pdfbox/">Generate a PDF in a Spring Boot with Apache PDFBox and Kotlin</a></li>
<li><a href="https://blog.codersee.com/rest-api-ktor-ktorm-postgresql/">REST API With Ktor, Ktorm, and PostgreSQL</a></li>
</ul>
<p><strong>Let me know in the comments section about your thoughts! 🙂</strong></p>
<p>The post <a href="https://blog.codersee.com/kotlin-pbkdf2-secure-password-hashing/">Kotlin PBKDF2 Secure Password Hashing</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.codersee.com/kotlin-pbkdf2-secure-password-hashing/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: blog.codersee.com @ 2026-04-24 13:08:21 by W3 Total Cache
-->