Android RSA 加密

2022-08-29 12:52:24 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

没想到被Android里的RSA加密折腾了几个小时,主要还是自己对RSA加密的原理不了解,然后网上相关的资料也少。 使用AndroidUtilCode工具类中的EncryptUtils.encryptRSA()加密后的数据怎么也不对,后来自己找了段加密代码,才总算是可以了,这里记录一下。

首先我们需要先 生成一个RSA的公钥和私钥。

RSA加密公钥

代码语言:javascript复制
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOCSZxJyD9BCPF E0AwT1v/qdv
lMhLKkNbnp1BIrh9bnfuv15mULugWq7ARtWtppZVLHu7H0No6vZQRN66BY3wWbll
NPZP2Qg2xV3ubXcDa5CtfdmDbPeN Ol4s97Gzcn7VL1 3NXzMRLAm1E64hqkrMfE
xpr5Okdai0szIb/EvwIDAQAB
-----END PUBLIC KEY-----

RSA加密私钥

代码语言:javascript复制
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAM4JJnEnIP0EI8X4
TQDBPW/ p2 UyEsqQ1uenUEiuH1ud 6/XmZQu6BarsBG1a2mllUse7sfQ2jq9lBE
3roFjfBZuWU09k/ZCDbFXe5tdwNrkK192YNs94346Xiz3sbNyftUvX7c1fMxEsCb
UTriGqSsx8TGmvk6R1qLSzMhv8S/AgMBAAECgYAK8Y96KSLmbYbc6BBm/tydi0An
fBabb3Y cpFVuVtlRi3Wn5GLC7S7krV/fwOwgo2vnno/ SwicYB9yPqvlMXyKtl0
kXlcQn6vj Qaf1EHy35Be4sEysTvVxW7eaHtrbIbQwc51YVUmbwX5sGnLL8579kK
zcQ15K9hpY gQ9tw0QJBAOx1dvvkOdGIrzBajpGB3V9Yu0Z4MZrl1AihzCZLgTov
3eAWtmDxa6y8ErYRXkZq8dC H9mnrBHN53Db6Gl1xfcCQQDfEA17x1A2M45z3suk
GbDbTy/u1K64RqsnubJWBXWzY1RO43cqP7Zul7edNgMdYpOGb6w4Z01i65ACcKDg
K6V5AkB7zymEzMRFZUctj0z0/UV3JhOw20BF9a7m8ijdqE06tVN8gQfvjJkvca5u
bHurbVW Ub6FjZi4HdLgMhToG0WTAkEAw6Zl3Tq LTxdZ150ybPK/yFezqH3uiQp
/YcQWAkj6rtl GflXsZRcoFaiOcWJlEPSqxqp3JcWzZ4ststEFLYKQJBAJqFy7HC
5vLOmAMqPzT1BP70MjrCFvJ80jeTIsIqfpJxxtmYthfjtmaM6UWnfDQhdbZ1bFvB
Ywuc/LNp25PThWc=
-----END PRIVATE KEY-----

然后附上RSA加密相关的代码

代码语言:javascript复制
fun main(){ 
   
	val idCard = "12345678"
	val result = rsaEncode(idCard)
	Log.i("Z-MMM", "result:$result")
}

fun rsaEncode(str: String): String? { 
   
    val publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOCSZxJyD9BCPF E0AwT1v/qdv
lMhLKkNbnp1BIrh9bnfuv15mULugWq7ARtWtppZVLHu7H0No6vZQRN66BY3wWbll
NPZP2Qg2xV3ubXcDa5CtfdmDbPeN Ol4s97Gzcn7VL1 3NXzMRLAm1E64hqkrMfE
xpr5Okdai0szIb/EvwIDAQAB"
   var outStr = ""
    try { 
   
        // base64编码的公钥
        val decoded: ByteArray = Base64.decode(publicKey, Base64.DEFAULT)
        val pubKey = KeyFactory.getInstance("RSA")
            .generatePublic(X509EncodedKeySpec(decoded)) as RSAPublicKey
        // RSA加密
        val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
        cipher.init(Cipher.ENCRYPT_MODE, pubKey)
        outStr = Base64.encodeToString(
            cipher.doFinal(str.toByteArray(charset("UTF-8"))),
            Base64.DEFAULT
        )
    } catch (e: Exception) { 
   
        e.printStackTrace()
    }
    return outStr
}

打印的结果

代码语言:javascript复制
mAHc2ZtZuzDrA295Aw4CpYhctlJA3NeC7xd0BgGRMVSzBL8WRYuxNiDK1CQXuQ7B/3wgqH72CbRw
    GjUndeZf4jIBm7GHj9xOa6GPbDhlTVeH4VAjSoEgxiRzh/0WW2KLFZjs4GCErjpMx x1U5EMIExV
    91OfiWcHCp72gns5tRo=

ras每次加密的结果都会变

验证加密结果 : 通过该网站我们可以对其进行解密,可以看到解密后的结果是12345678

感谢 Android RSA加密(Java后台给出公钥)

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/145729.html原文链接:https://javaforall.cn

0 人点赞