· 6 years ago · Feb 26, 2019, 04:34 AM
1- (NSData *)AES128DecryptWithKey:(NSString *)key
2{
3 // 'key' should be 16 bytes for AES128, will be null-padded otherwise
4 char keyPtr[kCCKeySizeAES128+1]; // room for terminator (unused)
5 bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
6
7 // fetch key data
8 [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
9
10 NSUInteger dataLength = [self length];
11
12 //See the doc: For block ciphers, the output size will always be less than or
13 //equal to the input size plus the size of one block.
14 //That's why we need to add the size of one block here
15 size_t bufferSize = dataLength + kCCBlockSizeAES128;
16 void *buffer = malloc(bufferSize);
17
18 size_t numBytesDecrypted = 0;
19 CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0,keyPtr, kCCKeySizeAES128,
20 NULL /* initialization vector (optional) */,
21 [self bytes], dataLength, /* input */
22 buffer, bufferSize, /* output */
23 &numBytesDecrypted);
24
25 if (cryptStatus == kCCSuccess)
26 {
27 //the returned NSData takes ownership of the buffer and will free it on deallocation
28 return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
29 }
30
31 free(buffer); //free the buffer;
32 return nil;
33}
34
35String mesg="hi";
36String aesKey="1EF5F2D644FBA8E4142778CD43D70BFA";
37
38byte[] raw =CryptoUtil.HexToByte(aesKey);
39
40SecretKeySpec skey = new SecretKeySpec(raw, "AES")
41
42byte[] encryptedmsg=encrypt(mesg.getBytes(), skey);
43String encodedMesg=b64.encode(encryptedmsg);
44
45private static byte[] encrypt(byte[] inpBytes,
46 SecretKey key) {
47 Cipher cipher
48 byte[] b
49 try{
50 println "inside encrypt"
51 cipher = Cipher.getInstance(xform);
52 cipher.init(Cipher.ENCRYPT_MODE, key);
53 b=cipher.doFinal(inpBytes);
54 println "encrypted bytearr::"+b
55 }
56 catch (Exception e) {
57 println "exception in encrypt:"+e.getMessage()
58 }
59 return b
60 }
61public static byte[] HexToByte(String hex) {
62 int len = hex.length();
63 if (len % 2 == 1) {
64 hex = "0" + hex;
65 len++;
66 }
67 byte[] value = new byte[len / 2];
68 for (int i = 0; i < len; i += 2) {
69 value[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character
70 .digit(hex.charAt(i + 1), 16));
71
72 }
73 return value;
74}
75
76CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
77 kCCAlgorithmAES128,
78 kCCOptionECBMode | kCCOptionPKCS7Padding,
79 keyPtr,
80 kCCKeySizeAES128,
81 NULL /* initialization vector (optional) */,
82 [self bytes], dataLength, /* input */
83 buffer, bufferSize, /* output */
84 &numBytesDecrypted);