Created
August 7, 2013 12:57
-
-
Save urcadox/6173812 to your computer and use it in GitHub Desktop.
RSA encryption in Scala
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 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to utilize this.