· 8 years ago · Dec 02, 2017, 05:12 PM
1/*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6package network_security;
7
8import java.io.UnsupportedEncodingException;
9import java.security.InvalidKeyException;
10import java.security.MessageDigest;
11import java.security.NoSuchAlgorithmException;
12import java.security.SecureRandom;
13import java.security.spec.KeySpec;
14import java.util.Arrays;
15import java.util.Base64;
16import javax.crypto.BadPaddingException;
17import javax.crypto.Cipher;
18import javax.crypto.IllegalBlockSizeException;
19import javax.crypto.KeyGenerator;
20import javax.crypto.NoSuchPaddingException;
21import javax.crypto.SecretKey;
22import javax.crypto.SecretKeyFactory;
23import javax.crypto.spec.PBEKeySpec;
24import javax.crypto.spec.SecretKeySpec;
25
26/**
27 *
28 * @author Admin
29 */
30public class SymmetricCryptor {
31
32 //hằng xác định thuáºt toán mã hóa
33 private final String Algorithm = "AES";
34 //khóa
35 private SecretKey secretKey;
36 //bá»™ sinh khóa theo thuáºt toán đã chá»n
37 private KeyGenerator keyGen;
38 //bộ mã
39 private Cipher cipher;
40
41 public SymmetricCryptor() {
42
43 }
44
45 // Tạo khóa không sỠdụng chuỗi
46 public void createSymetricKey() throws Exception {
47 //khởi tạo bộ sinh khóa
48 keyGen = KeyGenerator.getInstance(Algorithm);
49 //sinh khóa
50 secretKey = keyGen.generateKey();
51 }
52
53 // Tạo khóa sỠdụng chuỗi
54 public void createSymetricKeyFromPassword(String keystring) throws Exception {
55 byte[] key = new byte[16];
56 key = keystring.getBytes("UTF-8");
57 MessageDigest sha = MessageDigest.getInstance("SHA-1");
58 key = sha.digest(key);
59 key = Arrays.copyOf(key, 16);
60
61 secretKey = new SecretKeySpec(key, "AES");
62 }
63
64 public SecretKey getSecretKey() {
65 return secretKey;
66 }
67
68 public String encryptText(String msg, SecretKey key)
69 throws Exception {
70 //tạo bộ mã
71 cipher = Cipher.getInstance(Algorithm);
72 cipher.init(Cipher.ENCRYPT_MODE, key);
73 return Base64.getEncoder().encodeToString(
74 cipher.doFinal(msg.getBytes("UTF-8")));
75 }
76
77 public String decryptText(String msg, SecretKey key)
78 throws Exception {
79 cipher = Cipher.getInstance(Algorithm);
80 cipher.init(Cipher.DECRYPT_MODE, key);
81 return new String(cipher.doFinal(
82 Base64.getDecoder().decode(msg)), "UTF-8");
83 }
84
85 public static void main(String[] args) throws Exception {
86 SymmetricCryptor SC = new SymmetricCryptor();
87 SC.createSymetricKeyFromPassword("daicaphong");
88 String msg = "Nguyễn Văn An";
89 String encrypted_msg =
90 SC.encryptText(msg, SC.getSecretKey());
91 System.out.println("Plain text: " + msg);
92 System.out.println("Encrypted text: " + encrypted_msg);
93 String decrypted_msg =
94 SC.decryptText(encrypted_msg, SC.getSecretKey());
95 System.out.println("Decrypted text: " + decrypted_msg);
96 }
97}