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
171
172
173
174
175
/*
 * 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.cipher.asymetric;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
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 org.apache.commons.codec.binary.Base64;
 
/**
 *
 * @author STEPHANIE
 */
public class AsymetricCryptography {
 
    private Cipher cipher;
 
    public AsymetricCryptography() throws NoSuchAlgorithmException, NoSuchPaddingException {
//        this.cipher = Cipher.getInstance("RSA");
        this.cipher = Cipher.getInstance("RSA");
    }
 
    private PrivateKey getPrivate(String filename) throws Exception {
        byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    }
 
    private PublicKey getPublic(String filename) throws Exception {
        byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }
 
    private void encryptFile(byte[] input, File output, PrivateKey key)
            throws IOException, GeneralSecurityException {
        this.cipher.init(Cipher.ENCRYPT_MODE, key);
        writeToFile(output, this.cipher.doFinal(input));
    }
 
    private void decryptFile(byte[] input, File output, PublicKey key) {
        try {
            this.cipher.init(Cipher.DECRYPT_MODE, key);
            writeToFile(output, this.cipher.doFinal(input));
        } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | IOException ex) {
            Logger.getLogger(AsymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
 
    private void writeToFile(File output, byte[] toWrite)
            throws IllegalBlockSizeException, BadPaddingException, IOException {
        FileOutputStream fos = new FileOutputStream(output);
        fos.write(toWrite);
        fos.flush();
        fos.close();
    }
 
    private String encryptText(String msg, PrivateKey key)
            throws NoSuchAlgorithmException, NoSuchPaddingException,
            UnsupportedEncodingException, IllegalBlockSizeException,
            BadPaddingException, InvalidKeyException {
        this.cipher.init(Cipher.ENCRYPT_MODE, key);
        return Base64.encodeBase64String(cipher.doFinal(msg.getBytes("UTF-8")));
    }
 
    private String decryptText(String msg, PublicKey key)
            throws InvalidKeyException, UnsupportedEncodingException,
            IllegalBlockSizeException, BadPaddingException {
        this.cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(Base64.decodeBase64(msg)), "UTF-8");
    }
 
    public static String encryptText(String msg, String privateKeyPath) {
        try {
            AsymetricCryptography ac = new AsymetricCryptography();
            PrivateKey privateKey = ac.getPrivate(privateKeyPath);
            
            return ac.encryptText(msg, privateKey);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AsymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
             return null;
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(AsymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
             return null;
        } catch (Exception ex) {
            Logger.getLogger(AsymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
             return null;
        }
       
    }
    
     public static String decryptText(String msg, String publicKeyPath) {
        try {
            AsymetricCryptography ac = new AsymetricCryptography();
            PublicKey publicKey = ac.getPublic(publicKeyPath);
            
            return ac.decryptText(msg, publicKey);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AsymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
             return null;
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(AsymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
             return null;
        } catch (Exception ex) {
            Logger.getLogger(AsymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
             return null;
        }
       
    }
    
    public byte[] getFileInBytes(File f) throws IOException {
        FileInputStream fis = new FileInputStream(f);
        byte[] fbytes = new byte[(int) f.length()];
        fis.read(fbytes);
        fis.close();
        return fbytes;
    }
 
    /**
     * Fonction qui crypte un fichier
     * @param inputPath : chemin du fichier à crypter
     * @param outputPath : chemin vers les fichier crypté
     * @param privateKeyPath : chemin vers le fichier contenant la clé privée
     */
    public static void encryptFile(String inputPath, String outputPath, String privateKeyPath) {
        try {
            AsymetricCryptography ac = new AsymetricCryptography();
            PrivateKey privateKey = ac.getPrivate(privateKeyPath);
 
            ac.encryptFile(ac.getFileInBytes(new File(inputPath)),
                    new File(outputPath), privateKey);
        } catch (Exception ex) {
            Logger.getLogger(AsymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
 
    /**
     * Fonction qui décrypte un fichier
     * @param inputPath : chemin vers le fichier à décrypter
     * @param outputPath : chemin du fichier  contenant les données décryptées
     * @param publicKeyPath : chemin vers le fichier contenant la clé publique
     */
    public static void decryptFile(String inputPath, String outputPath, String publicKeyPath) {
        try {
            AsymetricCryptography ac = new AsymetricCryptography();
            PublicKey publicKey = ac.getPublic(publicKeyPath);
 
            ac.decryptFile(ac.getFileInBytes(new File(inputPath)),
                    new File(outputPath), publicKey);
        } catch (Exception ex) {
            Logger.getLogger(AsymetricCryptography.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
}