Created
December 31, 2019 16:43
-
-
Save GabriellCosta/212caff6910daedd4ab7ef7d97939237 to your computer and use it in GitHub Desktop.
Public key RSA cipher sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.rsatest | |
import android.security.keystore.KeyProperties | |
import android.util.Base64 | |
import java.security.Key | |
import java.security.KeyFactory | |
import java.security.spec.X509EncodedKeySpec | |
import javax.crypto.Cipher | |
private const val ALGORITHM = KeyProperties.KEY_ALGORITHM_RSA | |
class CipherMaker { | |
private val publicKey = | |
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvXmMURuCLR3Vx/slaQaQB/hXDxnhrKK+RjZpUtHBsNuU1PRsz3WlWuGhUSyd+jaxTKI6R+ftJduNfFriND9DP8+Zc+Fo5S+r7mD8lfjgprUo4hDHUtlGbMo8XxwW4ktJPuFRASeiW9lWyPIo0iXu1aJ7wQ9/6Z6KDtAowtpMi0JSqisGP/SzRDs7O+4oxhrvdcZD1XRm6IOv47CBLjX26c7juu+ZYc4XrpBSLUcF753m94xzHH1x9EigJNqHJWNuRE1ltJzbS+DWixnJyTomf6+mLZ09O5js5FUFkaAWKoe0D9j+eGNoqmePkh/lFpWt1ZF9Y4OZh3HGxM1o2oxXJwIDAQAB" | |
private val rsaKey by lazy { createKey() } | |
private val cipher by lazy { Cipher.getInstance(ALGORITHM) } | |
private fun createKey(): Key { | |
val publicKeyHardCoded = Base64.decode(publicKey, Base64.NO_WRAP) | |
val key = X509EncodedKeySpec(publicKeyHardCoded) //PKCS8EncodedKeySpec(publicKeyHardCoded) | |
return KeyFactory.getInstance(ALGORITHM) | |
.generatePublic(key) | |
} | |
fun encript(textToCipher: String): ByteArray { | |
cipher.init(Cipher.ENCRYPT_MODE, rsaKey) | |
return cipher.doFinal(textToCipher.toByteArray()) | |
} | |
fun decript(byteArray: ByteArray): String { | |
cipher.init(Cipher.DECRYPT_MODE, rsaKey) | |
val doFinal = cipher.doFinal(byteArray) | |
return String(doFinal) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.rsatest | |
import org.junit.Assert.assertNotEquals | |
import org.junit.Test | |
class CipherMakerTest { | |
val cipherMaker = CipherMaker() | |
@Test | |
fun cipherShouldNotBeEmpty() { | |
val encripted = cipherMaker.encript("Text") | |
assertNotEquals(0, encripted.size) | |
} | |
@Test | |
fun cipherShouldNotBeRevertedToSameValueDueToOnlyRSAPublicKey() { | |
val textToCipher = "Text" | |
val encripted = cipherMaker.encript(textToCipher) | |
val decripted = cipherMaker.decript(encripted) | |
assertNotEquals(textToCipher, decripted) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment