Skip to content

Instantly share code, notes, and snippets.

@Romain-P
Last active January 6, 2024 14:39
Show Gist options
  • Save Romain-P/96ecacdea9dc9a843947890d58f1da0d to your computer and use it in GitHub Desktop.
Save Romain-P/96ecacdea9dc9a843947890d58f1da0d to your computer and use it in GitHub Desktop.
ChaCha20-Poly1305 Java/Kotlin Implementation
import java.io.File
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.security.KeyFactory
import java.security.KeyPairGenerator
import java.security.SecureRandom
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
/* OUTPUT: [NB Ciphered][16B signature][12B nounce] */
fun encryptChachaPoly(plain: ByteArray, keyBytes: ByteArray, nonce: ByteArray = generateRandomByteArray(12)): ByteArray {
val key = SecretKeySpec(keyBytes, "ChaCha20-Poly1305")
val cipher = Cipher.getInstance("ChaCha20-Poly1305")
val iv = IvParameterSpec(nonce)
cipher.init(Cipher.ENCRYPT_MODE, key, iv)
val ciphered = cipher.doFinal(plain)
return ByteBuffer.allocate(ciphered.size + 12)
.put(ciphered)
.put(nonce)
.array()
}
/* INPUT: [NB Ciphered][16B signature][12B nounce] */
fun decryptChachaPoly(ciphered: ByteArray, keyBytes: ByteArray): ByteArray {
val key = SecretKeySpec(keyBytes, "ChaCha20-Poly1305")
val buffer: ByteBuffer = ByteBuffer.wrap(ciphered)
val encryptedText = ByteArray(ciphered.size - 12)
val nonce = ByteArray(12)
buffer.get(encryptedText)
buffer.get(nonce)
val cipher = Cipher.getInstance("ChaCha20-Poly1305")
val iv = IvParameterSpec(nonce)
cipher.init(Cipher.DECRYPT_MODE, key, iv)
return cipher.doFinal(encryptedText)
}
fun generateRandomByteArray(size: Int): ByteArray {
val secureRandom = SecureRandom()
val randomBytes = ByteArray(size)
secureRandom.nextBytes(randomBytes)
return randomBytes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment