· 6 years ago · Sep 28, 2019, 05:34 PM
1package ir.arcademy.sinadalvand.dagger2
2
3import android.util.Base64
4import java.security.NoSuchAlgorithmException
5import javax.crypto.Cipher
6import javax.crypto.NoSuchPaddingException
7import javax.crypto.spec.IvParameterSpec
8import javax.crypto.spec.SecretKeySpec
9
10
11class Zcript {
12
13 private val iv: String
14 var ivspec: IvParameterSpec
15 var keyspec: SecretKeySpec
16 private var cipher: Cipher? = null
17
18 private val SecretKey: String
19
20 constructor(iv: String, SecretKey: String) {
21 this.iv = iv
22 this.SecretKey = SecretKey
23
24 ivspec = IvParameterSpec(iv.toByteArray())
25 keyspec = SecretKeySpec(SecretKey.toByteArray(), "AES")
26
27
28 try {
29 cipher = Cipher.getInstance("AES/CBC/NoPadding")
30 } catch (e: NoSuchAlgorithmException) {
31 // TODO Auto-generated catch block
32 e.printStackTrace()
33 } catch (e: NoSuchPaddingException) {
34 // TODO Auto-generated catch block
35 e.printStackTrace()
36 }
37
38 }
39
40 @Throws(Exception::class)
41 fun encrypt(text: String?): String {
42 if (text == null || text.isEmpty())
43 throw Exception("Empty string")
44
45 var encrypted: ByteArray? = null
46
47 try {
48 cipher!!.init(Cipher.ENCRYPT_MODE, keyspec, ivspec)
49 encrypted = cipher!!.doFinal(padString(text).toByteArray())
50 } catch (e: Exception) {
51 throw Exception("[encrypt] " + e.message)
52 }
53
54
55
56 return Base64.encodeToString(encrypted, Base64.DEFAULT)
57 }
58
59
60 @Throws(Exception::class)
61 fun decrypt(code: String?): String {
62
63 if(code == null) throw Exception("String is null ! ")
64
65 val codes = Base64.decode(code, Base64.DEFAULT)
66
67 var decrypted: ByteArray? = null
68
69 try {
70 cipher!!.init(Cipher.DECRYPT_MODE, keyspec, ivspec)
71
72 decrypted = cipher!!.doFinal(codes)
73 //Remove trailing zeroes
74 if (decrypted!!.isNotEmpty()) {
75 var trim = 0
76 for (i in decrypted.indices.reversed()) if (decrypted[i].toInt() == 0) trim++
77
78 if (trim > 0) {
79 val newArray = ByteArray(decrypted.size - trim)
80 System.arraycopy(decrypted, 0, newArray, 0, decrypted.size - trim)
81 decrypted = newArray
82 }
83 }
84 } catch (e: Exception) {
85 throw Exception("[decrypt] " + e.message)
86 }
87
88 return String(decrypted)
89 }
90
91
92 private fun padString(source: String): String {
93 var source = source
94 val paddingChar: Char = 0.toChar()
95 val size = 16
96 val x = source.length % size
97 val padLength = size - x
98
99 for (i in 0 until padLength) {
100 source += paddingChar
101 }
102
103 return source
104 }
105}