Newer
Older
SmartKitchen / app / src / main / java / com / casic / br / utils / RSAUtils.kt
package com.casic.br.utils

import android.util.Base64
import java.security.*
import java.security.spec.InvalidKeySpecException
import java.security.spec.X509EncodedKeySpec
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.crypto.IllegalBlockSizeException
import javax.crypto.NoSuchPaddingException

object RSAUtils {
    //构建Cipher实例时所传入的的字符串,默认为"RSA/NONE/PKCS1Padding"
    private fun processData(srcData: ByteArray, key: Key): ByteArray? { //用来保存处理结果
        var resultBytes: ByteArray? = null
        try { //获取Cipher实例
            val cipher = Cipher.getInstance("RSA/None/PKCS1Padding")
            //初始化Cipher,mode指定是加密还是解密,key为公钥或私钥
            cipher.init(Cipher.ENCRYPT_MODE, key)
            //处理数据
            resultBytes = cipher.doFinal(srcData)
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        } catch (e: NoSuchPaddingException) {
            e.printStackTrace()
        } catch (e: InvalidKeyException) {
            e.printStackTrace()
        } catch (e: BadPaddingException) {
            e.printStackTrace()
        } catch (e: IllegalBlockSizeException) {
            e.printStackTrace()
        }
        return resultBytes
    }

    fun encryptDataByPublicKey(srcData: ByteArray, publicKey: PublicKey): String {
        val resultBytes =
            processData(srcData, publicKey)
        return Base64.encodeToString(resultBytes, Base64.DEFAULT)
    }

    fun keyStrToPublicKey(publicKeyStr: String?): PublicKey? {
        var publicKey: PublicKey? = null
        val keyBytes =
            Base64.decode(publicKeyStr, Base64.DEFAULT)
        val keySpec =
            X509EncodedKeySpec(keyBytes)
        try {
            val keyFactory = KeyFactory.getInstance("RSA")
            publicKey = keyFactory.generatePublic(keySpec)
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        } catch (e: InvalidKeySpecException) {
            e.printStackTrace()
        }
        return publicKey
    }
}