· 9 years ago · Nov 24, 2016, 06:02 AM
1private static String ALGORITHM = "AES";
2private static String DIGEST = "MD5";
3
4private static Cipher cipher;
5private static SecretKey password;
6private static IvParameterSpec IVParamSpec;
7private final static String pvtkey="GDNBCGDRFSC$%#%=";
8
9//16-byte private key
10private static byte[] IV = pvtkey.getBytes();
11
12public PassWordEncryptor() {
13 try {
14
15 //Encode digest
16 MessageDigest digest;
17 digest = MessageDigest.getInstance(DIGEST);
18 password = new SecretKeySpec(digest.digest(pvtkey.getBytes()), ALGORITHM);
19
20 //Initialize objects
21 cipher = Cipher.getInstance(TRANSFORMATION);
22 IVParamSpec = new IvParameterSpec(IV);
23
24 } catch (NoSuchAlgorithmException e) {
25 Log.i(Lams4gApp.TAG, "No such algorithm " + ALGORITHM);
26 } catch (NoSuchPaddingException e) {
27 System.out.println( "No such padding PKCS7"+ e);
28 }
29}
30/**
31Encryptor.
32
33@text String to be encrypted
34@return Base64 encrypted text
35
36*/
37public String encrypt(byte[] text) {
38
39 byte[] encryptedData;
40
41 try {
42
43 cipher.init(Cipher.ENCRYPT_MODE, password, IVParamSpec);
44 encryptedData = cipher.doFinal(text);
45
46 } catch (InvalidKeyException e) {
47 System.out.println( "Invalid key (invalid encoding, wrong length, uninitialized, etc)."+ e);
48 return null;
49 } catch (InvalidAlgorithmParameterException e) {
50 System.out.println( "Invalid or inappropriate algorithm parameters for " + ALGORITHM+ e);
51 return null;
52 } catch (IllegalBlockSizeException e) {
53 System.out.println( "The length of data provided to a block cipher is incorrect"+ e);
54 return null;
55 } catch (BadPaddingException e) {
56 System.out.println( "The input data but the data is not padded properly."+ e);
57 return null;
58 }
59 return Base64.encodeToString(encryptedData,Base64.DEFAULT);
60
61}
62
63- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv
64{
65 char keyPtr[kCCKeySizeAES128 + 1];
66 bzero(keyPtr, sizeof(keyPtr));
67 //keyPtr = [58,-43,46,33,-105,83,-80,-5,99,59,2,109,63,89,-59,-91];
68 key = [key MD5];
69 [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
70
71 char ivPtr[kCCBlockSizeAES128 + 1];
72 bzero(ivPtr, sizeof(ivPtr));
73 if (iv) {
74 [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
75 }
76
77 NSUInteger dataLength = [self length];
78 size_t bufferSize = dataLength + kCCBlockSizeAES128;
79 void *buffer = malloc(bufferSize);
80
81 size_t numBytesEncrypted = 0;
82 CCCryptorStatus cryptStatus = CCCrypt(operation,
83 kCCAlgorithmAES128,
84 kCCOptionPKCS7Padding,
85 keyPtr,
86 kCCBlockSizeAES128,
87 ivPtr,
88 [self bytes],
89 dataLength,
90 buffer,
91 bufferSize,
92 &numBytesEncrypted);
93 if (cryptStatus == kCCSuccess) {
94 return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
95 }
96 free(buffer);
97 return nil;
98}