· 7 years ago · Mar 28, 2018, 01:42 PM
1public byte[] encryptDecrypt(String jsonData, String publicKey) throws Exception
2 {
3 Security.addProvider(new BouncyCastleProvider());
4 SecretKey secKey = getSecretEncryptionKey();
5
6 cipherText = encryptText(jsonData, secKey);
7 return cipherText;
8 }
9
10 public static SecretKey getSecretEncryptionKey() throws Exception
11 {
12 KeyGenerator generator = KeyGenerator.getInstance("AES");
13 generator.init(256);
14 SecretKey secKey = generator.generateKey();
15 return secKey;
16 }
17 public static byte[] encryptText(String plainText, SecretKey secKey) throws Exception
18 {
19 // AES defaults to AES/ECB/PKCS5Padding in Java 7
20 SecretKeySpec skeySpec = new SecretKeySpec(secKey.getEncoded(), "AES/ECB/PKCS7Padding");
21
22 Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
23 aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
24 return aesCipher.doFinal(plainText.getBytes());
25 }
26
27INT32 Security::decrypt(UINT8 *ciphertext, INT32 ciphertext_len, UINT8 *key,
28 UINT8 *iv, UINT8 *plaintext)
29{
30 EVP_CIPHER_CTX *ctx;
31
32 INT32 len;
33
34 INT32 plaintext_len;
35
36 /* Create and initialise the context */
37 if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
38
39if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_ecb(), 0, Key, NULL)) {
40 printf("n ERROR!! n");
41 return -1;
42 }
43
44 /* Provide the message to be decrypted, and obtain the plaintext output.
45 * EVP_DecryptUpdate can be called multiple times if necessary
46 */
47 if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
48 handleErrors();
49 plaintext_len = len;
50
51 /* Finalise the decryption. Further plaintext bytes may be written at
52 * this stage.
53 */
54 if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
55 plaintext_len += len;
56
57 /* Clean up */
58 EVP_CIPHER_CTX_free(ctx);
59
60 return plaintext_len;
61}