Kotlin 中的密码学:加密与哈希示例

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Kotlin 中的密码学:加密与哈希



Kotlin 作为 JVM 的现代语言,可以访问 Java Cryptography Architecture (JCA) 的全部功能。这使得可以实现对称加密(AES、DES)和非对称加密(RSA),以及密码学哈希函数(SHA-256、MD5)和数字签名。在本文中,我们将分析 Kotlin 中密码学的实际应用示例,这些示例可用于保护 Web 应用程序、移动开发和后端服务中的数据。



所有代码示例均使用 Java 内置功能,因此它们是跨平台的,无需额外库。



1. Kotlin 中的 AES 对称加密



对称加密使用相同的密钥进行加密和解密。AES(高级加密标准)算法是安全性的黄金标准。我们来看一个使用 CBC 模式和 PKCS5Padding 对字符串进行加密的示例。



import javax.crypto.Cipherimport javax.crypto.KeyGeneratorimport javax.crypto.SecretKeyimport javax.crypto.spec.IvParameterSpecimport javax.crypto.spec.SecretKeySpecimport java.util.Base64

fun generateAESKey(): SecretKey { val keyGen = KeyGenerator.getInstance("AES") keyGen.init(256) // 密钥长度:128、192 或 256 位 return keyGen.generateKey()}

fun encryptAES(plainText: String, secretKey: SecretKey, iv: ByteArray): String { val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") val ivSpec = IvParameterSpec(iv) cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec) val encrypted = cipher.doFinal(plainText.toByteArray()) return Base64.getEncoder().encodeToString(encrypted)}

fun decryptAES(encryptedText: String, secretKey: SecretKey, iv: ByteArray): String { val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") val ivSpec = IvParameterSpec(iv) cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec) val decoded = Base64.getDecoder().decode(encryptedText) val decrypted = cipher.doFinal(decoded) return String(decrypted)}

fun main() { val key = generateAESKey() val iv = ByteArray(16) // 初始化向量(AES 为 16 字节) // 在实际项目中,iv 应该是随机的,并与密文一起传输 val original = "你好,Kotlin!" val encrypted = encryptAES(original, key, iv) val decrypted = decryptAES(encrypted, key, iv) println("原文:$original") println("加密后:$encrypted") println("解密后:$decrypted")}


重要提示: 初始化向量 (IV) 每次加密都应该是随机的,并与加密数据一起公开传输。切勿在生产环境中使用固定的 IV。



2. Kotlin 中的 RSA 非对称加密



RSA 使用一对密钥:公钥用于加密,私钥用于解密。这非常适合在各方之间安全传输数据。



import java.security.KeyPairGeneratorimport java.security.PrivateKeyimport java.security.PublicKeyimport javax.crypto.Cipherimport java.util.Base64

fun generateRSAKeyPair(): Pair<PublicKey, PrivateKey> { val keyGen = KeyPairGenerator.getInstance("RSA") keyGen.initialize(2048) // 推荐的密钥大小 val keyPair = keyGen.generateKeyPair() return Pair(keyPair.public, keyPair.private)}

fun encryptRSA(plainText: String, publicKey: PublicKey): String { val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding") cipher.init(Cipher.ENCRYPT_MODE, publicKey) val encrypted = cipher.doFinal(plainText.toByteArray()) return Base64.getEncoder().encodeToString(encrypted)}

fun decryptRSA(encryptedText: String, privateKey: PrivateKey): String { val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding") cipher.init(Cipher.DECRYPT_MODE, privateKey

推荐