Android RSA加密

109 阅读1分钟
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 {

                }
            }
        }
    }


    /**RSA算法*/
    var RSA = "RSA";
    /**加密方式,android的*/
// public static final String TRANSFORMATION = "RSA/None/NoPadding";
    /**加密方式,标准jdk的*/
    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"))
    }

    /**
     * 随机生成RSA密钥对
     *
     * @param keyLength 密钥长度,范围:512~2048
     *                  一般1024
     * @return
     */
    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
        }
    }
}