Skip to content

Instantly share code, notes, and snippets.

@urcadox
Created August 7, 2013 12:57
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save urcadox/6173812 to your computer and use it in GitHub Desktop.
Save urcadox/6173812 to your computer and use it in GitHub Desktop.
RSA encryption in Scala
package util
import java.security._
import java.security.spec.X509EncodedKeySpec
import javax.crypto._
import org.apache.commons.codec.binary.Base64
object RSA {
def decodePublicKey(encodedKey: String): Option[PublicKey] = {
this.decodePublicKey(
(new Base64()).decode(encodedKey)
)
}
def decodePublicKey(encodedKey: Array[Byte]): Option[PublicKey] = {
scala.util.control.Exception.allCatch.opt {
val spec = new X509EncodedKeySpec(encodedKey)
val factory = KeyFactory.getInstance("RSA")
factory.generatePublic(spec)
}
}
def encrypt(key: PublicKey, data: Array[Byte]): Array[Byte] = {
val cipher = Cipher.getInstance("RSA")
cipher.init(Cipher.ENCRYPT_MODE, key)
cipher.doFinal(data)
}
def encryptB64(key: PublicKey, data: Array[Byte]): String = {
(new Base64()).encodeAsString(this.encrypt(key, data))
}
def encryptB64(key: PublicKey, data: String): String = {
this.encryptB64(key, data.getBytes)
}
}
@nilay214
Copy link

nilay214 commented Dec 7, 2021

how to utilize this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment