Kenmegne
6 days ago 4575de680f208fe13833116470664c7252e84bc8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.megatim.module.encryption.aes.symetric;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
 
/**
 *
 * @author STEPHANIE
 */
public class SymetricCryptography {
 
    private static final String SALT = "hdbgshdbvnc";
    private static final String HASH_ALGORITHM = "PBKDF2WithHmacSHA256";
    private static final String ALGORITHM = "AES";
    private static final int HASH_ITERATIONS = 65536;
 
    /**
     * Fonction qui sert à chiffrer
     *
     * @param inputPath : chemin vers le fichier à chiffrer
     * @param keyLength : {128,192,256}
     * @param outputPath : chemin vers le resutlat du chiffrement
     * @param password : clé de chiffrement
     */
    public static void encryptFile(String password, int keyLength, String inputPath, String outputPath) {
        File file = new File(inputPath);
 
        try {
            if (file.exists()) {
                /* Chiffre le fichier */
                cryptOrDecryptFile(Cipher.ENCRYPT_MODE, password, keyLength, file, new File(outputPath));
            }
        } catch (Exception ex) {
            Logger.getLogger(SymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
 
    /**
     * Fonction qui sert à déchiffrer
     *
     * @param inputPath : chemin du fichier à déchiffrer
     * @param keyLength
     * @param outputPath : chemin où stocké le resultat du déchiffrement
     * @param password : clé de déchiffrement
     */
    public static void decryptFile(String password, int keyLength, String inputPath, String outputPath) {
        File file = new File(inputPath);
 
        try {
        /* Déchiffre le fichier  */
        cryptOrDecryptFile(Cipher.DECRYPT_MODE, password, keyLength, file,
                new File(outputPath));
 
        } catch (Exception ex) {
            Logger.getLogger(SymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }
    }
 
    
    private static void cryptOrDecryptFile(int mode, String password, int keyLength, File inputFile, File outputFile)
            throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, 
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {
 
        SecretKey secret = getKeyFromPassword(password, SALT, keyLength);
            /* Utilisation de l'algorithme AES */
            Cipher aesCipher = Cipher.getInstance(ALGORITHM);
            aesCipher.init(mode, secret);
 
            if (!outputFile.exists()) {
                Files.createFile(outputFile.toPath());
            }
 
            FileInputStream inputStream = new FileInputStream(inputFile);
            FileOutputStream outputStream = new FileOutputStream(outputFile);
 
            byte[] buffer = new byte[64];
            int bytesRead;
 
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byte[] output = aesCipher.update(buffer, 0, bytesRead);
                if (output != null) {
                    outputStream.write(output);
                }
            }
            byte[] outputBytes = aesCipher.doFinal();
            if (outputBytes != null) {
                outputStream.write(outputBytes);
            }
            inputStream.close();
            outputStream.close();
    }
 
    /**
     * Méthode servant à générer une clé secrète à partir du mot de passe de l'utilisateur
     * @param password : mot de passe à partir duquel on veut générer la clé sécrète
     * @param salt : valeur servant à renforcer la sécurité de la clé sécrète
     * @param keylength : longueur de la clé en bit
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException 
     */
    private static SecretKey getKeyFromPassword(String password, String salt, int keylength)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
 
        SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGORITHM);
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), HASH_ITERATIONS, keylength);
        SecretKey secret = new SecretKeySpec(factory.generateSecret(spec)
                .getEncoded(), ALGORITHM);
        return secret;
    }
 
    
    public static String encryptString(String password, int keyLength, String strToEncrypt) {
 
        try {
            SecretKey secret = getKeyFromPassword(password, SALT, keyLength);
 
            /* Utilisation de l'algorithme AES */
            Cipher aesCipher = Cipher.getInstance(ALGORITHM);
            aesCipher.init(Cipher.ENCRYPT_MODE, secret);
 
            /* Chiffre la chaine de charactères */
            return Base64.getEncoder().encodeToString(aesCipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception ex) {
            Logger.getLogger(SymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
            return "";
        }
    }
 
    public static String decryptString(String password, int keyLength, String strToDecrypt) {
 
        try {
             SecretKey secret = getKeyFromPassword(password, SALT, keyLength);
 
            /* Utilisation de l'algorithme AES */
            Cipher aesCipher = Cipher.getInstance(ALGORITHM);
            aesCipher.init(Cipher.DECRYPT_MODE, secret);
 
            /* Déchiffre le fichier  */
            return new String(aesCipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); 
 
        } catch (Exception ex) {
            Logger.getLogger(SymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
            return "";
        }
    }
}