Java/Kotlin Encrypt AES key with private and public key

与世无争的帅哥 提交于 2019-12-08 13:04:17

问题


so I lately saw a video from computerphile where they said that when using encryption you should be using AES keys and encrypt this key with public and private key. This means: I have a public key from someone else, and my own private key.

The reason behind encrypting it with your own private key is, that this verifies that the message has to be comming from me, because no one else has my private key, so encryption with my public key can only work on messages comming from me.

Problem is that after my first encryption, the byte array outcomming becomes too long and I cant encrypt it another time. Is there a way around this?

This is my code:

val aKey = generateAESKey()

val kG = KeyPairGenerator.getInstance("RSA")
kG.initialize(2048)
val own = kG.genKeyPair()
val strange = kG.genKeyPair()

String(aKey.encoded).encryptRSA(strange.public).encryptRSA(own.public)

fun generateAESKey(): Key {
val generator = KeyGenerator.getInstance("AES")
generator.init(128)
return generator.generateKey()

fun String.encryptRSA(key: Key): String {
    val encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
    encryptCipher.init(Cipher.ENCRYPT_MODE, key)
    val cipherText = encryptCipher.doFinal(this.toByteArray(charset("UTF-
    8")))
    return String(cipherText)
}

fun String.decryptRSA(key: Key): String {
    val bytes = this.toByteArray()
    val decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
    decryptCipher.init(Cipher.DECRYPT_MODE, key)
    return String(decryptCipher.doFinal(bytes), charset("UTF-8"))
}

This for example gives me the following error:

Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:344)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at de.intektor.kentai_http_common.util.EncryptionKt.encryptRSA(encryption.kt:30)
at de.intektor.test.TestKt.main(Test.kt:19)

Of course this is just a testcase.

来源:https://stackoverflow.com/questions/46205964/java-kotlin-encrypt-aes-key-with-private-and-public-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!