· 9 years ago · Aug 31, 2016, 10:04 PM
1public string Encrypt(string InputForEncryption, string Password, string IV)
2 {
3 IBuffer buffInputForEncryption = CryptographicBuffer.ConvertStringToBinary(InputForEncryption, BinaryStringEncoding.Utf8);
4
5 IBuffer buffPassword = CryptographicBuffer.ConvertStringToBinary(Password, BinaryStringEncoding.Utf8);
6
7 IBuffer buffIV = CryptographicBuffer.ConvertStringToBinary(IV, BinaryStringEncoding.Utf8);
8
9 KeyDerivationAlgorithmProvider DerAlgo = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
10 KeyDerivationParameters KeyPara = KeyDerivationParameters.BuildForPbkdf2(buffIV, 1024);
11
12 CryptographicKey KeyPassword = DerAlgo.CreateKey(buffPassword);
13 IBuffer buffMatPassword = CryptographicEngine.DeriveKeyMaterial(KeyPassword, KeyPara, 32);
14
15 CryptographicKey KeyIV = DerAlgo.CreateKey(buffPassword);
16 IBuffer buffMatIV = CryptographicEngine.DeriveKeyMaterial(KeyIV, KeyPara, 16);
17
18 SymmetricKeyAlgorithmProvider SymAlgo = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
19 CryptographicKey KeySym = SymAlgo.CreateSymmetricKey(buffMatPassword);
20
21 IBuffer buffRESULT = CryptographicEngine.Encrypt(KeySym, buffInputForEncryption, buffMatIV);
22
23 string Result = CryptographicBuffer.EncodeToBase64String(buffRESULT);
24 return Result;
25 }
26
27private Cipher cipher;
28private SecretKey secretKey;
29private IvParameterSpec ivParameterSpec;
30
31int iterationCount = 1024;
32int keyStrength = 128;
33
34private String sampleInputForPassSaltIV = "Abcd1234Abcd1234";
35
36private String encryptInput = "helloAES";
37private String encryptedOutput = "";
38private String decryptedOutput = "";
39
40public Boolean initializeEncryption() throws Exception {
41 String secretKeyAlgorithm = "PBKDF2WithHmacSHA1";
42
43 SecretKeyFactory secretKeyFactory;
44 KeySpec keySpec;
45 SecretKey secretKeyTemp;
46
47 String passPhrase = sampleInputForPassSaltIV;
48 String keySalt = sampleInputForPassSaltIV;
49
50 secretKeyFactory = SecretKeyFactory.getInstance(secretKeyAlgorithm);
51 keySpec = new PBEKeySpec(passPhrase.toCharArray(), keySalt.getBytes(), iterationCount, keyStrength);
52 secretKeyTemp = secretKeyFactory.generateSecret(keySpec);
53 secretKey = new SecretKeySpec(secretKeyTemp.getEncoded(), "AES");
54
55 byte[] IV = sampleInputForPassSaltIV.getBytes();
56 ivParameterSpec = new IvParameterSpec(IV);
57
58 cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
59
60 return true;
61}
62
63private void encrypt(String dataToEncrypt) throws Exception {
64 if (dataToEncrypt.length() > 0) {
65 byte[] UTF8Data;
66 cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
67 UTF8Data = cipher.doFinal(dataToEncrypt.getBytes());
68 encryptedOutput = Base64.encodeToString(UTF8Data, 0);
69
70 Toast toast = Toast.makeText(context, "Encrypted Text : " + encryptedOutput, Toast.LENGTH_LONG);
71 toast.show();
72 }
73}