· 7 years ago · Apr 21, 2018, 03:44 AM
1import javax.crypto.{Cipher, SecretKey, SecretKeyFactory}
2import javax.crypto.spec.DESKeySpec
3
4import sun.misc.{BASE64Decoder, BASE64Encoder}
5
6/**
7 * Created by @author yuanjchen on 4/12/18
8 */
9object DesEncryptionExample extends App {
10 val key = "i_am_a_testing_key" // key must be longer than 8 chars
11 val secretKey: SecretKey = SecretKeyFactory.getInstance("des").generateSecret(new DESKeySpec(key.getBytes))
12
13 val plainText = "Hello, World"
14
15 val encoded = DESEncode(plainText)
16 println(s"text:$plainText, encoded text:$encoded")
17 assert(plainText != encoded)
18
19 val decoded = DESDecode(encoded)
20 assert(plainText == decoded)
21
22 def DESEncode(content: String): String = {
23 val cipher = Cipher.getInstance("des")
24 cipher.init(Cipher.ENCRYPT_MODE, secretKey)
25 cipher.doFinal(content.getBytes)
26 new BASE64Encoder().encode(cipher.doFinal(content.getBytes("utf-8")))
27 }
28
29 def DESDecode(content: String): String = {
30 val cipher = Cipher.getInstance("des")
31 cipher.init(Cipher.DECRYPT_MODE, secretKey)
32 new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(content)),"utf-8")
33 }
34
35}