Skip to content

Commit cbf45a8

Browse files
committed
完善加密解密方法
1 parent c93a07c commit cbf45a8

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed
Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,38 @@
11
package com.example.wan.android.utils
22

3+
import android.util.Base64
4+
import javax.crypto.Cipher
5+
import javax.crypto.SecretKey
6+
import javax.crypto.spec.SecretKeySpec
7+
38
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)
619
}
720

821
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")
1138
}

app/src/main/java/com/example/wan/android/utils/SerializableUtils.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ package com.example.wan.android.utils
33
import com.blankj.utilcode.util.ConvertUtils
44
import java.io.Serializable
55

6-
fun Serializable.toByteArray(): ByteArray {
6+
fun Serializable.serializable2ByteArray(): ByteArray {
77
return ConvertUtils.serializable2Bytes(this)
88
}
99

10-
fun ByteArray.toObject(): Any {
10+
fun ByteArray.byteArray2Serializable(): Any {
1111
return ConvertUtils.bytes2Object(this)
1212
}

0 commit comments

Comments
 (0)