Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
26548 amit.gupta 1
package com.spice.profitmandi.service.integrations.spicemoney;
2
 
3
 
4
import java.io.UnsupportedEncodingException;
5
import java.security.MessageDigest;
6
import java.security.NoSuchAlgorithmException;
7
import java.util.Arrays;
8
import java.util.Base64;
9
 
10
import javax.crypto.Cipher;
11
import javax.crypto.spec.SecretKeySpec;
12
 
13
public class Aes {
14
 
15
    private static SecretKeySpec secretKey;
16
    private static byte[] key;
17
 
18
    public static void setKey(String myKey)
19
    {
20
        MessageDigest sha = null;
21
        try {
22
            key = myKey.getBytes("UTF-8");
23
            sha = MessageDigest.getInstance("SHA-1");
24
            key = sha.digest(key);
25
            key = Arrays.copyOf(key, 16);
26
            secretKey = new SecretKeySpec(key, "AES");
27
        }
28
        catch (NoSuchAlgorithmException e) {
29
            e.printStackTrace();
30
        }
31
        catch (UnsupportedEncodingException e) {
32
            e.printStackTrace();
33
        }
34
    }
35
 
36
    public static String encrypt(String strToEncrypt, String secret)
37
    {
38
        try
39
        {
40
            setKey(secret);
41
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
42
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
43
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
44
        }
45
        catch (Exception e)
46
        {
47
            System.out.println("Error while encrypting: " + e.toString());
48
        }
49
        return null;
50
    }
51
 
52
    public static String decrypt(String strToDecrypt, String secret)
53
    {
54
        try
55
        {
56
            setKey(secret);
57
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
58
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
59
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
60
        }
61
        catch (Exception e)
62
        {
63
            System.out.println("Error while decrypting: " + e.toString());
64
        }
65
        return null;
66
    }
67
    public static void main(String[] args) {
68
    	final String secretKey = "spice@#$054";
69
 
70
 
71
		  String originalString = "Spicewallet@#12345"; 
72
		  String encryptedString = Aes.encrypt(originalString, secretKey) ;
73
 
74
      String decryptedString = Aes.decrypt("fd9489c2-6e89-446d-98dd-ca056fa58792", "spice@#$054") ;         
75
 
76
       System.out.println(decryptedString);
77
 
78
    }
79
}