Created
June 16, 2020 21:27
-
-
Save GabriellCosta/01ccb0eafa95da93f0b90f36bea65d84 to your computer and use it in GitHub Desktop.
Key Pair EncDen in scratch file
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
import java.security.* | |
import java.security.spec.PKCS8EncodedKeySpec | |
import java.security.spec.X509EncodedKeySpec | |
import javax.crypto.Cipher | |
private val ALGORITHM = "RSA" | |
fun generateKeyPair(): KeyPair { | |
val keyGen: KeyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM) | |
val random: SecureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN") | |
keyGen.initialize(512, random) | |
return keyGen.generateKeyPair() | |
} | |
fun encrypt(publicKey: ByteArray?, inputData: ByteArray?): ByteArray { | |
val key = KeyFactory.getInstance(ALGORITHM) | |
.generatePublic(X509EncodedKeySpec(publicKey)) | |
val cipher: Cipher = Cipher.getInstance(ALGORITHM) | |
cipher.init(Cipher.ENCRYPT_MODE, key) | |
return cipher.doFinal(inputData) | |
} | |
fun decrypt(privateKey: ByteArray?, inputData: ByteArray?): ByteArray { | |
val key = KeyFactory.getInstance(ALGORITHM) | |
.generatePrivate(PKCS8EncodedKeySpec(privateKey)) | |
val cipher: Cipher = Cipher.getInstance(ALGORITHM) | |
cipher.init(Cipher.DECRYPT_MODE, key) | |
return cipher.doFinal(inputData) | |
} | |
val keyPair = generateKeyPair() | |
val public = keyPair.public.encoded | |
val private = keyPair.private.encoded | |
val targetString = "Oi eu sou o tigrão" | |
val encrypted = encrypt(public, targetString.toByteArray()) | |
println("Resultado encriptado -> ${String(encrypted)}") | |
val decrypt = decrypt(private, encrypted) | |
val decryptedResult = String(decrypt) | |
println("Resultado decriptado -> $decryptedResult") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment