-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurityUtil.kt
More file actions
77 lines (53 loc) · 2.46 KB
/
SecurityUtil.kt
File metadata and controls
77 lines (53 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.example.testsmpp
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import java.security.MessageDigest
import android.util.Base64
class SecurityUtil {
companion object {
fun encryptText(text: String, key: String): String {
val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
// Generate a random initialization vector (IV)
val iv = ByteArray(cipher.blockSize)
val ivSpec = IvParameterSpec(iv)
// Create the secret key from the provided key
val secretKeySpec = SecretKeySpec(key.toByteArray(Charsets.UTF_8), "AES")
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec)
val encryptedBytes = cipher.doFinal(text.toByteArray(Charsets.UTF_8))
// Encode the encrypted bytes using Base64
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT)
}
fun decryptText(encryptedText: String, key: String): String {
val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
// Generate a random initialization vector (IV)
val iv = ByteArray(cipher.blockSize)
val ivSpec = IvParameterSpec(iv)
// Create the secret key from the provided key
val secretKeySpec = SecretKeySpec(key.toByteArray(Charsets.UTF_8), "AES")
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivSpec)
val encryptedBytes = Base64.decode(extractText(encryptedText), Base64.DEFAULT)
val decryptedBytes = cipher.doFinal(encryptedBytes)
return String(decryptedBytes, Charsets.UTF_8)
}
private fun extractText(input: String): String? {
val startSymbol = "$$"
val endSymbol = "$$"
val startIndex = input.indexOf(startSymbol)
val endIndex = input.lastIndexOf(endSymbol)
if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
return input.substring(startIndex + startSymbol.length, endIndex)
}
return null
}
fun hashText(text: String): String {
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(text.toByteArray())
val result = StringBuilder()
for (byte in digest) {
result.append(String.format("%02x", byte))
}
return result.toString()
}
}
}