class MainActivity : AppCompatActivity() {
private val publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC41cJ0pyvkSLjTK0BRXOx/0MWW" +
"r/8awOJxrD9woU4b4EepSmvOhyWtj9XT2Gvl0wvbgLu1v28rbegpaHnFQS1AfBfN" +
"YMHfiiJksVskEfR8yX4em9EIpm2Y+ZRSPvT8Zx0Z0eceRYi5by1vsSFBxMaChs9q" +
"HyNGlJPJxSDbB3xZlwIDAQAB"
private val privateKeyStr = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALjVwnSnK+RIuNMr" +
"QFFc7H/QxZav/xrA4nGsP3ChThvgR6lKa86HJa2P1dPYa+XTC9uAu7W/bytt6Clo" +
"ecVBLUB8F81gwd+KImSxWyQR9HzJfh6b0QimbZj5lFI+9PxnHRnR5x5FiLlvLW+x" +
"IUHExoKGz2ofI0aUk8nFINsHfFmXAgMBAAECgYA4nuLOsVc0u0JDDgDJ69lW3jFp" +
"E8jl/ShhAg79BazTxUSui2my/puAK4upNab35ErBlxHpfxcjCqwP4z1KO8kMbld6" +
"I0zTHBjvBBRGKlhG4D7jzIYksCw7gGYpvhTl6+QM2jsW9Vtzbk1hgxN7uDPhAVfg" +
"7wo4Zw8oKXtFmEqbQQJBAOnp5AF6yJ9t8NeroqgxgndgtaoW0GthHgrFF2Z/I0Ee" +
"LfZn7tzFSA7dvbMMG6ygxbk7Ny2wAjKIZonsmAjtM18CQQDKSY0D/WfnIke3kk0m" +
"P9NLXAuCJvMJaHLQl7U0zIH4A5q6fx54MAZk1yuIzoVGnoE2VZXboWJBnDQ/Fnxh" +
"w3zJAkEAnj1iyHl2pRvr1QrAY8Xye63J14HNhwbRGvoQBX+2qsOu1kWjOmifgacS" +
"QMDNK/ArMk7T2i16nxLVQzLx+v/0QwJANubNcgbFu3KPWmBHthjehPZ/XRyrG6OQ" +
"fdKe6KyUnbaEuRclMuN96MKJW0EJ5QfB8/g4ivp7C2mUuIamzXXcGQJBAKNsWCGi" +
"GfnU7DF4Q372/aIFPvJr6mIompKEqPl663sQJNW6EgC2iAlnCctbwHCH0aZ5/Syr" +
"0LeB/XTW7ewXq50="
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
try {
doAsync {
val str = "我是原文"
var text = "<font color=#ff0000>原文:</font> $str<br/>"
val cipher = Cipher.getInstance("RSA") // 确定算法
// 格式化私钥
val pkcs8EncodedKeySpec = PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyStr))
var keyFactory = KeyFactory.getInstance("RSA")
val privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec)
// 格式化公钥
val x509EncodedKeySpec = X509EncodedKeySpec(Base64.decodeBase64(publicKeyStr))
keyFactory = KeyFactory.getInstance("RSA")
val publicKey = keyFactory.generatePublic(x509EncodedKeySpec)
text += " <strong><font color=#ff0000>私钥解密 公钥解密</font></strong><br/>"
//私钥加密
cipher.init(Cipher.ENCRYPT_MODE, privateKey)
var result = cipher.doFinal(str.toByteArray())
var encodeStr = Base64.encodeBase64String(result)
text = "$text<br/>私钥加密:<br/>$encodeStr<br/>"
//公钥解密
cipher.init(Cipher.DECRYPT_MODE, publicKey);
var decodeStr = String(cipher.doFinal(result))
text = "$text<br/>公钥解密:<br/>$decodeStr<br/><br/>"
text += " <strong><font color=#ff0000>公钥解密 私钥解密</font></strong><br/>"
//公钥加密
cipher.init(Cipher.ENCRYPT_MODE, publicKey)
result = cipher.doFinal(str.toByteArray())
encodeStr = Base64.encodeBase64String(result)
text = "$text<br/>公钥加密:<br/>$encodeStr<br/>"
//私钥解密
cipher.init(Cipher.DECRYPT_MODE, privateKey);
decodeStr = String(cipher.doFinal(result))
text = "$text<br/>私钥解密:<br/>$decodeStr<br/>\n"
runOnUiThread { textView11?.text = Html.fromHtml(text) }
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
效果如图:
ssss
网友评论