问题
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