Skip to content

Commit e56f7fd

Browse files
committed
add cryptography static helper
1 parent 02a2b8b commit e56f7fd

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package land.fx.fula;
2+
3+
import android.util.Base64;
4+
5+
import java.io.UnsupportedEncodingException;
6+
import java.security.InvalidAlgorithmParameterException;
7+
import java.security.InvalidKeyException;
8+
import java.security.NoSuchAlgorithmException;
9+
import java.security.spec.InvalidKeySpecException;
10+
import java.security.spec.InvalidParameterSpecException;
11+
12+
import javax.crypto.BadPaddingException;
13+
import javax.crypto.Cipher;
14+
import javax.crypto.IllegalBlockSizeException;
15+
import javax.crypto.NoSuchPaddingException;
16+
import javax.crypto.SecretKey;
17+
import javax.crypto.spec.SecretKeySpec;
18+
19+
public class Cryptography {
20+
public static String encryptMsg(String message, SecretKey secret)
21+
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
22+
Cipher cipher = null;
23+
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
24+
cipher.init(Cipher.ENCRYPT_MODE, secret);
25+
byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8"));
26+
return Base64.encodeToString(cipherText, Base64.NO_WRAP);
27+
}
28+
public static String decryptMsg(String cipherText, SecretKey secret)
29+
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
30+
Cipher cipher = null;
31+
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
32+
cipher.init(Cipher.DECRYPT_MODE, secret);
33+
byte[] decode = Base64.decode(cipherText, Base64.NO_WRAP);
34+
String decryptString = new String(cipher.doFinal(decode), "UTF-8");
35+
return decryptString;
36+
}
37+
public static SecretKey generateKey(String key)
38+
throws NoSuchAlgorithmException, InvalidKeySpecException
39+
{
40+
SecretKeySpec secret;
41+
secret = new SecretKeySpec(key.getBytes(), "AES");
42+
return secret;
43+
}
44+
}

0 commit comments

Comments
 (0)