|
1 | 1 | package com.example.wan.android.utils
|
2 | 2 |
|
| 3 | +import android.util.Base64 |
| 4 | +import javax.crypto.Cipher |
| 5 | +import javax.crypto.SecretKey |
| 6 | +import javax.crypto.spec.SecretKeySpec |
| 7 | + |
3 | 8 | fun String.encrypt(key: String): String {
|
4 |
| - // todo 假装已经加密 |
5 |
| - return this |
| 9 | + // 1. 生成密钥 |
| 10 | + val secretKey = generateKey(key) |
| 11 | + val cipher = Cipher.getInstance("AES") |
| 12 | + cipher.init(Cipher.ENCRYPT_MODE, secretKey) |
| 13 | + // 2. 把字符串转为字节数组 |
| 14 | + val toByteArray = this.toByteArray(Charsets.UTF_8) |
| 15 | + // 3. 使用 AES 加密字节数组 |
| 16 | + val encryptedBytes = cipher.doFinal(toByteArray) |
| 17 | + // 4. 使用 Base64 把字节数组编码成字符串,以便存储或传输 |
| 18 | + return Base64.encodeToString(encryptedBytes, Base64.NO_WRAP) |
6 | 19 | }
|
7 | 20 |
|
8 | 21 | fun String.decrypt(key: String): String {
|
9 |
| - // todo 假装我在解密 |
10 |
| - return this |
| 22 | + // 1. 生成密钥 |
| 23 | + val secretKey = generateKey(key) |
| 24 | + val cipher = Cipher.getInstance("AES") |
| 25 | + cipher.init(Cipher.DECRYPT_MODE, secretKey) |
| 26 | + // 2. 使用 Base64 把字符串解码成字节数组 |
| 27 | + val decodeBase64 = Base64.decode(this, Base64.NO_WRAP) |
| 28 | + // 3. 使用 AES 解密字节数组 |
| 29 | + val decryptedBytes = cipher.doFinal(decodeBase64) |
| 30 | + // 4. 把字节数组还原字符串 |
| 31 | + return String(decryptedBytes, Charsets.UTF_8) |
| 32 | +} |
| 33 | + |
| 34 | +// 生成一个 16 字节的密钥 |
| 35 | +private fun generateKey(key: String): SecretKey { |
| 36 | + val keyBytes = key.toByteArray(Charsets.UTF_8).copyOf(16) // AES 要求密钥长度为 16 字节 |
| 37 | + return SecretKeySpec(keyBytes, "AES") |
11 | 38 | }
|
0 commit comments