package com.india.ui.login
import android.app.Application
import android.util.Base64
import androidx.lifecycle.MutableLiveData
import app.common.AppRuntime
import app.common.base.BaseResult
import app.common.base.BaseViewModel
import app.common.repository.Repo
import java.security.KeyFactory
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.PublicKey
import java.security.spec.X509EncodedKeySpec
import javax.crypto.Cipher
class PhoneLoginActivityVM(application: Application) : BaseViewModel(application) {
val vCode = MutableLiveData("")
fun setPwd() = io2main {
val vCode = vCode.value
val keyPair = generateRSAKeyPair(1024);
val publicKey = keyPair!!.public
val publicKeyBytes = publicKey.encoded
val publicKeyString: String = Base64.encodeToString(publicKeyBytes, Base64.DEFAULT)
val encryptBytes = encryptByPublicKey(vCode.toString(), publicKeyString);
if (vCode.isNullOrEmpty()) {
return@io2main BaseResult.error(
BaseResult.Companion.ErrorCode.TOAST_SHORT, "请输入密码"
)
} else {
return@io2main Repo.api.reaKey().also {
if (it.isSuccess()) {
val encryptBytes = encryptByPublicKey(vCode.toString(), it.data!!["key"]!!.toString());
Repo.api.setPwd(encryptBytes, AppRuntime.getUpPwd()).also {
if (it.isSuccess()) {
} else {
}
}
} else {
}
}
}
}
var RSA = "RSA";
var TRANSFORMATION = "RSA/ECB/PKCS1Padding";
fun encryptByPublicKey(data: String, key: String): String {
val keyByte = Base64.decode(key.toByteArray(charset("UTF-8")), Base64.NO_WRAP)
val keyFactory = KeyFactory.getInstance("RSA")
val publicKey = keyFactory.generatePublic(X509EncodedKeySpec(keyByte))
val cp = Cipher.getInstance(TRANSFORMATION)
cp.init(Cipher.ENCRYPT_MODE, publicKey)
val cpBy = cp.doFinal(data.toByteArray(charset("UTF-8")))
return String(Base64.encode(cpBy, Base64.NO_WRAP), charset("UTF-8"))
}
fun generateRSAKeyPair(keyLength: Int): KeyPair? {
var keyPair: KeyPair? = null
try {
val keyPairGenerator = KeyPairGenerator.getInstance("RSA")
keyPairGenerator.initialize(keyLength);
keyPair = keyPairGenerator.generateKeyPair();
return keyPair
} catch (e: Exception) {
return null
}
}
}