package com.xw.yunwei.extension
|
|
import android.util.Base64
|
import java.nio.charset.StandardCharsets
|
import java.security.KeyFactory
|
import java.security.MessageDigest
|
import java.security.PublicKey
|
import java.security.spec.X509EncodedKeySpec
|
import java.text.SimpleDateFormat
|
import java.util.Locale
|
import javax.crypto.Cipher
|
import javax.crypto.Mac
|
import javax.crypto.SecretKey
|
import javax.crypto.spec.SecretKeySpec
|
|
//扩展函数 MD5加密 耗时操作
|
fun String.md5(): String {
|
return try {
|
val md = MessageDigest.getInstance("MD5")
|
val digest = md.digest(toByteArray())
|
digest.joinToString("") {
|
"%02x".format(it)
|
}
|
} catch (e: Exception) {
|
e.printStackTrace()
|
""
|
}
|
}
|
|
//扩展函数 通过HmacSHA256加密
|
fun String.encryptByHmacSHA256(key: String): String {
|
try {
|
val key: SecretKey =
|
SecretKeySpec(
|
key.toByteArray(StandardCharsets.UTF_8),
|
"HmacSHA256"
|
)
|
val mac = Mac.getInstance(key.algorithm)
|
mac.init(key)
|
val sig = mac.doFinal(toByteArray(StandardCharsets.UTF_8))
|
val hex = java.lang.StringBuilder(sig.size * 2)
|
for (b in sig) {
|
hex.append(Character.forDigit((b.toInt() shr 4) and 0xF, 16))
|
hex.append(Character.forDigit(b.toInt() and 0xF, 16))
|
}
|
return hex.toString()
|
} catch (e: Exception) {
|
throw RuntimeException(e)
|
}
|
}
|
|
//扩展函数 通过公钥RSA加密
|
fun String.encryptByPublicKey(publicKeyText: String): String {
|
return try {
|
// 1. 解码 Base64 编码的公钥文本获取 DER 格式字节数组
|
// 对应 Python: base64.b64decode(public_key_text)
|
val derPublicKeyBytes = Base64.decode(publicKeyText, Base64.DEFAULT)
|
|
// 2. 加载 DER 格式的公钥
|
// 对应 Python: serialization.load_der_public_key(...)
|
// 在 Java/Kotlin 中,通常使用 X509EncodedKeySpec 来加载 DER 格式的公钥
|
val keySpec = X509EncodedKeySpec(derPublicKeyBytes)
|
|
// 注意:这里使用 "RSA" 算法。如果你的后端严格要求 PKCS#1 格式,
|
// 可能需要使用 "RSA" 并配合 Bouncy Castle 库,但 X509EncodedKeySpec 通常能处理大多数标准公钥。
|
val keyFactory = KeyFactory.getInstance("RSA")
|
val publicKey: PublicKey = keyFactory.generatePublic(keySpec)
|
|
// 3. 使用 RSA 加密
|
// 对应 Python: public_key.encrypt(..., padding.PKCS1v15())
|
val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
|
cipher.init(Cipher.ENCRYPT_MODE, publicKey)
|
|
// 将文本转换为字节数组并加密
|
val encryptedBytes = cipher.doFinal(toByteArray(StandardCharsets.UTF_8))
|
|
// 4. 返回 Base64 编码的加密结果
|
// 对应 Python: base64.b64encode(ciphertext).decode('utf-8')
|
Base64.encodeToString(encryptedBytes, Base64.NO_WRAP)
|
} catch (e: Exception) {
|
e.printStackTrace()
|
""
|
}
|
}
|
|
//扩展函数 日期字符串更换格式
|
fun String.dateChangePattern(oldPattern: String, newPattern: String): String {
|
return try {
|
SimpleDateFormat(oldPattern, Locale.getDefault()).parse(this)?.let {
|
SimpleDateFormat(newPattern, Locale.getDefault()).format(it)
|
} ?: this
|
} catch (e: Exception) {
|
e.printStackTrace()
|
this
|
}
|
}
|