IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Sécurité Java Discussion :

Cryptage/Decryptage de String


Sujet :

Sécurité Java

  1. #1
    Membre averti
    Inscrit en
    Mai 2006
    Messages
    41
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 41
    Par défaut Cryptage/Decryptage de String
    Bonjour,

    En fait je cherche à faire quelque chose d'assez simple.
    J'aimerais crypter de manière asymétrique une chaine de caractère sur un serveur, puis sur un autre serveur (poscédant la clé publique correspondante), décrypter cette meme chaine à l'intérieur d'une JSP ou autre.

    J'ai trouvé cette méthode pour crypter/decrypter un fichier apres avoir générer le duo-clé publique/clé privé proposée par Razgriz ici

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    /*
     * RSAEncryptor.java
     *
     * Created on 17 juin 2006, 15:58
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */
     
    package Security;
     
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.security.GeneralSecurityException;
    import java.security.Key;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
     
    /**
     *
     * @author Absil Romain
     */
    public class RSAEncryptor
    {
     
        /**
         * Generate a pair of key, write the public in publicOutputFileName and the
         * private in privateOutputFileName.
         * @param publicOutputFileName the file where the public key is written in.
         * @param privateOutputFileName the file where the private key is written in.
         **/
        public static void generateKeys(String publicInputFileName, 
                String privateOutputFileName)
        {
            try
            {
                KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
                SecureRandom random = new SecureRandom();
                pairgen.initialize(2048, random);
                KeyPair keyPair = pairgen.generateKeyPair();
     
                ObjectOutputStream out = new ObjectOutputStream(
                        new FileOutputStream(publicInputFileName));
                out.writeObject(keyPair.getPublic());
                out.close();
     
                out = new ObjectOutputStream(
                        new FileOutputStream(privateOutputFileName));
                out.writeObject(keyPair.getPrivate());
                out.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
     
        /**
         * Encrytps the file inputFileName and saves the result in the file 
         * outputFileName, with the specified key keyFileName.
         * @param inputFileNane the file to encrypt.
         * @param outputFileName the file to save the encrypting result in.
         * @param keyFileName the key to use to encrypt the file.
         **/
        public static void encryptFile(String inputFileName, String outputFileName, 
                String keyFileName)
        {
            try
            {
                KeyGenerator keygen = KeyGenerator.getInstance("AES");
                SecureRandom random = new SecureRandom();
                keygen.init(random);
                SecretKey key = keygen.generateKey();
     
                //emballe avec la clé publique RSA
                ObjectInputStream keyIn = new ObjectInputStream(
                        new FileInputStream(keyFileName));
                Key publicKey = (Key)keyIn.readObject();
                keyIn.close();
     
                Cipher cipher = Cipher.getInstance("RSA");            
                cipher.init(Cipher.WRAP_MODE, publicKey);
                byte[] wrappedKey = cipher.wrap(key);
                DataOutputStream out = new DataOutputStream(
                        new FileOutputStream(outputFileName));
                out.writeInt(wrappedKey.length);
                out.write(wrappedKey);
     
                InputStream in = new FileInputStream(inputFileName);
                cipher = cipher.getInstance("AES");
                cipher.init(Cipher.ENCRYPT_MODE, key);
                crypt(in, out, cipher);
                in.close();
                out.close();
            } 
     
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
     
        /**
         * Decrytps the file inputFileName and saves the result in the file 
         * outputFileName, with the specified key keyFileName.
         * @param inputFileName the file to decrypt.
         * @param outputFileName the file to save the decrypting result in.
         * @param keyFileName the key to use to decrypt the file.
         **/
        public static void decryptFile(String inputFileName, String outputFileName, 
                String keyFileName)
        {
            try
            {
                DataInputStream in = new DataInputStream(
                        new FileInputStream(inputFileName));
                int length = in.readInt();
                byte[] wrappedKey = new byte[length];
                in.read(wrappedKey, 0, length);
     
                //déballe avec la clé RSA
                ObjectInputStream keyIn = new ObjectInputStream(
                        new FileInputStream(keyFileName));
                Key privateKey = (Key)keyIn.readObject();
                keyIn.close();
     
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.UNWRAP_MODE, privateKey);
                Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
     
                OutputStream out = new FileOutputStream(outputFileName);
                cipher = cipher.getInstance("AES");
                cipher.init(Cipher.DECRYPT_MODE, key);
     
                crypt(in, out, cipher);
                in.close();
                out.close();            
            } 
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
     
        }
     
        private static void crypt(InputStream in, OutputStream out, Cipher cipher)
            throws IOException, GeneralSecurityException
        {
            int blockSize = cipher.getBlockSize();
            int outputSize = cipher.getOutputSize(blockSize);
            byte[] inBytes = new byte[blockSize];
            byte[] outBytes = new byte[outputSize];
     
            int inLength = 0;
            boolean done = false;
            while(!done)
            {
                inLength = in.read(inBytes);
                if(inLength == blockSize)
                {
                    int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
                    out.write(outBytes, 0, outLength);
                }
                else
                    done = true;
            }
     
            if(inLength > 0)
                outBytes = cipher.doFinal(inBytes, 0, inLength);
            else
                outBytes = cipher.doFinal();
            out.write(outBytes);
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    //Génération de clés : 
            RSAEncryptor.generateKeys("public key.key","private key.key");
     
            //Encryptage
    	RSAEncryptor.encryptFile("The Chronicles Of Narnia.avi","Encrypt.encrypt","public key.key");
     
            //Décryptage
    	RSAEncryptor.decryptFile("Encrypt.encrypt","Chronicles 2.avi"
    Merci pour vos suggestions.

    Aswat

  2. #2
    Membre éclairé Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut
    Tu utilise la méthode getBytes() de la classe String, ça te renvoie un tableau de bytes et tu passe ça au cipher. Pour décrypter tu fait new String (decryptedbytes) et ça va mercher.

    Sinon beaucoup plus simple : j'ai posté une autre classe sympatique quicrypte bien (un stream de cryptage), elle se trouev ici.

    Y a l'input stream et l'output stream.
    Note : une amélioration serait d'écrire la clé AES en début de fichier crypté. Pour décryptae, il suffit de la décrypter avec la RSA et ensuite de décrypter le reste du fichier avec la clé AES.

    Tu n'as qu'à faire stream.writeObject(monString) et a marche.

  3. #3
    Membre averti
    Inscrit en
    Mai 2006
    Messages
    41
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 41
    Par défaut
    Citation Envoyé par Razgriz
    Tu utilise la méthode getBytes() de la classe String, ça te renvoie un tableau de bytes et tu passe ça au cipher. Pour décrypter tu fait new String (decryptedbytes) et ça va mercher.

    Sinon beaucoup plus simple : j'ai posté une autre classe sympatique quicrypte bien (un stream de cryptage), elle se trouev ici.

    Y a l'input stream et l'output stream.
    Note : une amélioration serait d'écrire la clé AES en début de fichier crypté. Pour décryptae, il suffit de la décrypter avec la RSA et ensuite de décrypter le reste du fichier avec la clé AES.

    Tu n'as qu'à faire stream.writeObject(monString) et a marche.
    Attend je ne suis pas sur que tu est compris ce que je cherche a faire. En fait j'aimerais balader une chaine de caractère dans un cookie. Cette chaine doit être cryptée et décryptée. Les solutions que tu m'indiques semblent s'orienter vers le cryptage/décryptage de fichiers ce qui ne me sert pas vraiment. Il faudrait que j'utilise pour cela une clé coté serveur 1 et une autre clé coté appli (serveur 2) pour décoder.

    Je suis un peu paumé....

  4. #4
    Membre averti
    Inscrit en
    Mai 2006
    Messages
    41
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 41
    Par défaut
    j'ai une classe qui fait presque ce que je veux. En fait j'aimerais remplacer le cryptage symétrique par un cryptage asymétrique. Et surtout j'aimerais pouvoir avoir une clé privé sur le serveur qui crypte et une clé publique sur le serveur qui decrypte

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    package com.atosorigin.opiam.auth.cas.security;
     
    import java.io.UnsupportedEncodingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.SecretKey;
     
    public class Encryption {
    	Cipher ecipher;
        Cipher dcipher;
     
        public Encryption(SecretKey key) {
        	try {
                ecipher = Cipher.getInstance("DES");
                dcipher = Cipher.getInstance("DES");
                ecipher.init(Cipher.ENCRYPT_MODE, key);
                dcipher.init(Cipher.DECRYPT_MODE, key);
     
            } catch (javax.crypto.NoSuchPaddingException e) {
            } catch (java.security.NoSuchAlgorithmException e) {
            } catch (java.security.InvalidKeyException e) {
            }
        }
     
        /**
         * @param str
         * @return
         */
        public String encrypt(String str) {
            try {
                // Encode the string into bytes using utf-8
                byte[] utf8 = str.getBytes("UTF8");
     
                // Encrypt
                byte[] enc = ecipher.doFinal(utf8);
     
                // Encode bytes to base64 to get a string
                return new sun.misc.BASE64Encoder().encode(enc);
            } catch (javax.crypto.BadPaddingException e) {
            } catch (IllegalBlockSizeException e) {
            } catch (UnsupportedEncodingException e) {
            }
            return null;
        }
     
        /**
         * @param str
         * @return
         */
        public String decrypt(String str) {
            try {
                // Decode base64 to get bytes
                byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
     
                // Decrypt
                byte[] utf8 = dcipher.doFinal(dec);
     
                // Decode using utf-8
                return new String(utf8, "UTF8");
            } catch (javax.crypto.BadPaddingException e) {
            } catch (IllegalBlockSizeException e) {
            } catch (UnsupportedEncodingException e) {
            } catch (java.io.IOException e) {
            }
            return null;
        }
    }

  5. #5
    Membre averti
    Inscrit en
    Mai 2006
    Messages
    41
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 41
    Par défaut
    bon j'ai généré un couple de clé avec OpenSSL de cette manière :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    openssl genrsa -out private.der 2048 
    openssl rsa -in private.der -pubout -outform DER -out public.der
    ensuite j'essaye d'utiliser ma clé privé pour chiffrer :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    package com.atosorigin.opiam.auth.cas.security;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
     
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
     
    public class Main {
     
    	/**
             * @param args
             */
    	public static void main(String[] args) {
     
    		String passwordEnClair = "motDePasse";
    		String passwordCrypte = "vide";
    		File keyFile = new File("private.der");
    		byte[] encodedKey = new byte[(int)keyFile.length()];
     
    		try {
    			new FileInputStream(keyFile).read(encodedKey);
    		} catch (FileNotFoundException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		} catch (IOException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
     
    		PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
     
    		KeyFactory kf;
    		try {
    			kf = KeyFactory.getInstance("RSA");
    			PrivateKey pk;
    			try {
    				pk = kf.generatePrivate(privateKeySpec);
    			} catch (InvalidKeySpecException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
    			Cipher rsa;
     
    			try {
    				rsa = Cipher.getInstance("RSA");
     
    				try {
    	                // Encode the string into bytes using utf-8
    	                byte[] utf8 = passwordEnClair.getBytes("UTF8");
     
    	                // Encrypt
    	                byte[] enc = rsa.doFinal(utf8);
     
    	                // Encode bytes to base64 to get a string
    	                passwordCrypte = new sun.misc.BASE64Encoder().encode(enc);
    	            } catch (javax.crypto.BadPaddingException e) {
    	            } catch (IllegalBlockSizeException e) {
    	            } catch (UnsupportedEncodingException e) {
    	            }
    			} catch (NoSuchAlgorithmException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			} catch (NoSuchPaddingException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
     
    		} catch (NoSuchAlgorithmException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    		System.out.println(passwordCrypte);
    	}
    }
    mais j'obtient cette erreur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    Quelqun a déjàs essayé de faire ceci ?

  6. #6
    Membre averti
    Inscrit en
    Mai 2006
    Messages
    41
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 41
    Par défaut
    Bon j'y suis presque, le cryptage fonctionne mais j'arrive pas a utiliser ma clé privé pour décrypter ...


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    package com.atosorigin.opiam.auth.cas.security;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.InvalidKeyException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
     
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
     
    public class Main {
     
    	/**
             * @param args
             */
    	public static void main(String[] args) {
     
    		String passwordEnClair = "motDePasse";
    		String passwordCrypte = "vide";
    		String passwordDeCrypte = "vide";
     
    		File publicKeyFile = new File("public2.der");
    		byte[] encodedPublicKey = new byte[(int)publicKeyFile.length()];
     
    		try {
    			new FileInputStream(publicKeyFile).read(encodedPublicKey);
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
     
    		KeyFactory kf;
    		try {
    			kf = KeyFactory.getInstance("RSA");
    			PublicKey pk;
    			try {
    				pk = kf.generatePublic(publicKeySpec);
    				Cipher rsa;
    				try {
    					rsa = Cipher.getInstance("RSA");
    					try {
    						rsa.init(Cipher.ENCRYPT_MODE, pk);
    					} catch (InvalidKeyException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					try {
    			            // Encode the string into bytes using utf-8
    			            byte[] utf8 = passwordEnClair.getBytes("UTF8");
     
    			            // Encrypt
    			            byte[] enc = rsa.doFinal(utf8);
     
    			            // Encode bytes to base64 to get a string
    			            passwordCrypte =  new sun.misc.BASE64Encoder().encode(enc);
    			        } catch (javax.crypto.BadPaddingException e) {
    			        } catch (IllegalBlockSizeException e) {
    			        } catch (UnsupportedEncodingException e) {
    			        }
    				} catch (NoSuchAlgorithmException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				} catch (NoSuchPaddingException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			} catch (InvalidKeySpecException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		System.out.println(passwordCrypte);
     
    		//************************************************************************
    		//Décryptage
    		//************************************************************************
     
    		File privateKeyFile = new File("private2.pem");
    		byte[] encodedPrivateKey = new byte[(int)privateKeyFile.length()];
     
    		try {
    			new FileInputStream(privateKeyFile).read(encodedPrivateKey);
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
     
    		KeyFactory kf2;
    		try {
    			kf2 = KeyFactory.getInstance("RSA");
    			PrivateKey pk2;
    			try {
    				pk2 = kf2.generatePrivate(privateKeySpec);
    				Cipher rsa2;
    				try {
    					rsa2 = Cipher.getInstance("RSA");
    					try {
    						rsa2.init(Cipher.DECRYPT_MODE, pk2);
    					} catch (InvalidKeyException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					try {
    			            // Decode base64 to get bytes
    			            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(passwordCrypte);
     
    			            // Decrypt
    			            byte[] utf8 = rsa2.doFinal(dec);
     
    			            // Decode using utf-8
    			            passwordDeCrypte = new String(utf8, "UTF8");
    			        } catch (javax.crypto.BadPaddingException e) {
    			        } catch (IllegalBlockSizeException e) {
    			        } catch (UnsupportedEncodingException e) {
    			        } catch (java.io.IOException e) {
    			        }
     
    				} catch (NoSuchAlgorithmException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				} catch (NoSuchPaddingException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			} catch (InvalidKeySpecException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		System.out.println("**********\nInitial: " + passwordEnClair + "\nCrypté: " + passwordCrypte + "\nDécrypté: " + passwordDeCrypte);
     
    	}
    }
    Par contre j'ai une exception :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    	at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:175)
    	at java.security.KeyFactory.generatePrivate(KeyFactory.java:322)
    	at com.atosorigin.opiam.auth.cas.security.Main.main(Main.java:116)
    Caused by: java.security.InvalidKeyException: invalid key format
    	at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:324)
    	at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:350)
    	at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:74)
    	at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:58)
    	at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:274)
    	at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:171)
    	... 2 more
    Je comprend pas j'ai du me planter quelque part .... cette fois-ci j'ai testé en créant les clés de deux manières différentes :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    openssl genrsa -out private.der 2048 
    openssl rsa -in private.der -pubout -outform DER -out public.der
    et
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    openssl genrsa -out private2.pem 2048 
    openssl rsa -in private2.pem -pubout -outform DER -out public2.der
    Quelqun pour m'aider ??

    aswat

  7. #7
    Membre éclairé Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut
    C'est tout à fait normal.

    Les clés RSA en gros contiennt des nombres, en java le fichier est évrit d'une certaine manoère (sérialisation) et ton logiciel le fait d'une autre manière. Donc évidement la clé de ton logiciel n'est pas reconnue comme une clé par mon programme. Utilise generateKeys de mon code pour le faire.

    D'accord c'est pas super POO comme classe, c'était un des premiers modèles pour voir si ça fonctionnait, j'ai une belle classe bien faite si tu veux mais tout est là sinon.

  8. #8
    Membre averti
    Inscrit en
    Mai 2006
    Messages
    41
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 41
    Par défaut
    Non tinquiete pas je n'ais pas la prétention de coder POO comme un pro, loing de là. Je voulais juste essayer de passer par un outil externe pour générer les clés mais c'est pas indispensable pour moi. Je vais essayer avec ta methode.
    Par contre ce que je ne comprend pas c'est que la clé "publique" est bien lue par mon programme, seule la clé privé ne l'est pas. Sinon, pour la manière dont je lit ces clés tu vois un truc qui cloche ??

    je veux bien voir ta classe bien faite par curiosité et surtout pour apprendre, merci.

    aswat

  9. #9
    Membre averti
    Inscrit en
    Mai 2006
    Messages
    41
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 41
    Par défaut
    En fait ca ne marche pas, du coup mon programme ne lit aucune des deux clés. Je m'explique j'appel ta methode generateKeys puis je les utilisent dans mon programme. J'ai une erreur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: DerInputStream.getLength(): lengthTag=109, too big.
    	at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:163)
    	at java.security.KeyFactory.generatePublic(KeyFactory.java:284)
    	at com.atosorigin.opiam.auth.cas.security.Main.crypt(Main.java:72)
    	at com.atosorigin.opiam.auth.cas.security.Main.main(Main.java:40)
    Caused by: java.security.InvalidKeyException: IOException: DerInputStream.getLength(): lengthTag=109, too big.
    	at sun.security.x509.X509Key.decode(X509Key.java:380)
    	at sun.security.x509.X509Key.decode(X509Key.java:386)
    	at sun.security.rsa.RSAPublicKeyImpl.<init>(RSAPublicKeyImpl.java:65)
    	at sun.security.rsa.RSAKeyFactory.generatePublic(RSAKeyFactory.java:256)
    	at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:159)
    voici le code en entier :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    176
    177
    package com.atosorigin.opiam.auth.cas.security;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.InvalidKeyException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
     
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
     
    public class Main {
     
    	/**
             * @param args
             */
    	public static void main(String[] args) {
     
    		String passwordEnClair = "motDePasse";
    		String passwordCrypte = "vide";
    		String passwordDeCrypte = "vide";
    		//************************************************************************
    		//Génération des clés
    		//************************************************************************
    		RSAEncryptor.generateKeys("encryptionKey.key","decryptionKey.key");
     
    		System.out.println("Initial: " + passwordEnClair);
    		//************************************************************************
    		//Cryptage
    		//************************************************************************
    		passwordCrypte = crypt(passwordEnClair);
    		System.out.println("Crypté: " + passwordCrypte);
    		//************************************************************************
    		//Décryptage
    		//************************************************************************
    		passwordDeCrypte = decrypt(passwordCrypte);
    		System.out.println("Décrypté: " + passwordDeCrypte);
     
    	}
     
    	private static String crypt(String passwordEnClair)
    	{
    		File encryptionKeyFile = new File("encryptionKey.key");
    		byte[] encodedEncryptionKey = new byte[(int)encryptionKeyFile.length()];
     
    		try {
    			new FileInputStream(encryptionKeyFile).read(encodedEncryptionKey);
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		X509EncodedKeySpec encryptionKeySpec = new X509EncodedKeySpec(encodedEncryptionKey);
     
    		KeyFactory kf;
    		try {
    			kf = KeyFactory.getInstance("RSA");
    			PublicKey pk;
    			try {
    				pk = kf.generatePublic(encryptionKeySpec);
    				Cipher rsa;
    				try {
    					rsa = Cipher.getInstance("RSA");
    					try {
    						rsa.init(Cipher.ENCRYPT_MODE, pk);
    					} catch (InvalidKeyException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					try {
    			            // Encode the string into bytes using utf-8
    			            byte[] utf8 = passwordEnClair.getBytes("UTF8");
     
    			            // Encrypt
    			            byte[] enc = rsa.doFinal(utf8);
     
    			            // Encode bytes to base64 to get a string
    			            return new sun.misc.BASE64Encoder().encode(enc);
    			        } catch (javax.crypto.BadPaddingException e) {
    			        } catch (IllegalBlockSizeException e) {
    			        } catch (UnsupportedEncodingException e) {
    			        }
    				} catch (NoSuchAlgorithmException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				} catch (NoSuchPaddingException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			} catch (InvalidKeySpecException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
     
    	private static String decrypt(String passwordCrypte)
    	{
    		File privateKeyFile = new File("decryptionKey.key");
    		byte[] encodedPrivateKey = new byte[(int)privateKeyFile.length()];
     
    		try {
    			new FileInputStream(privateKeyFile).read(encodedPrivateKey);
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		X509EncodedKeySpec privateKeySpec = new X509EncodedKeySpec(encodedPrivateKey);
     
    		KeyFactory kf2;
    		try {
    			kf2 = KeyFactory.getInstance("RSA");
    			PrivateKey pk2;
    			try {
    				pk2 = kf2.generatePrivate(privateKeySpec);
    				Cipher rsa2;
    				try {
    					rsa2 = Cipher.getInstance("RSA");
    					try {
    						rsa2.init(Cipher.DECRYPT_MODE, pk2);
    					} catch (InvalidKeyException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					try {
    			            // Decode base64 to get bytes
    			            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(passwordCrypte);
     
    			            // Decrypt
    			            byte[] utf8 = rsa2.doFinal(dec);
     
    			            // Decode using utf-8
    			            return new String(utf8, "UTF8");
    			        } catch (javax.crypto.BadPaddingException e) {
    			        } catch (IllegalBlockSizeException e) {
    			        } catch (UnsupportedEncodingException e) {
    			        } catch (java.io.IOException e) {
    			        }
     
    				} catch (NoSuchAlgorithmException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				} catch (NoSuchPaddingException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			} catch (InvalidKeySpecException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    }
    Ca plante a cette instruction :

    pk = kf.generatePublic(encryptionKeySpec);

    J'aurais pas oublié un paramètre ?

  10. #10
    Membre averti
    Inscrit en
    Mai 2006
    Messages
    41
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 41
    Par défaut
    Bon ben c'a y est j'y suis parvenu.
    ci-joint ma classe:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    package com.atosorigin.opiam.auth.cas.security;
     
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.security.InvalidKeyException;
    import java.security.Key;
    import java.security.NoSuchAlgorithmException;
     
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
     
    public class Main {
     
    	/**
             * @param args
             */
    	public static void main(String[] args) {
     
    		String passwordEnClair = "motDePasse";
    		String passwordCrypte = "vide";
    		String passwordDeCrypte = "vide";
    		//************************************************************************
    		//Génération des clés
    		//************************************************************************
    		//RSAEncryptor.generateKeys("encryptionKey.key","decryptionKey.key");
     
    		System.out.println("Initial: " + passwordEnClair);
    		//************************************************************************
    		//Cryptage
    		//************************************************************************
    		passwordCrypte = crypt(passwordEnClair);
    		System.out.println("Crypté: " + passwordCrypte);
    		//************************************************************************
    		//Décryptage
    		//************************************************************************
    		passwordDeCrypte = decrypt(passwordCrypte);
    		System.out.println("Décrypté: " + passwordDeCrypte);
     
    	}
     
    	private static String crypt(String passwordEnClair)
    	{
    		//	emballe avec la clé publique RSA
            ObjectInputStream keyIn;
    		try {
    			keyIn = new ObjectInputStream(new FileInputStream("encryptionKey.key"));
    			Key encryptionKey;
    			try {
    				encryptionKey = (Key)keyIn.readObject();
    				Cipher rsa;
    				try {
    					rsa = Cipher.getInstance("RSA");
    					try {
    						rsa.init(Cipher.ENCRYPT_MODE, encryptionKey);
    						byte[] utf8 = passwordEnClair.getBytes("UTF8");
     
    						// Encrypt
    						byte[] enc;
    						try {
    							enc = rsa.doFinal(utf8);
    							// Encode bytes to base64 to get a string
    							return new sun.misc.BASE64Encoder().encode(enc);
     
    						} catch (IllegalBlockSizeException e) {
    							e.printStackTrace();
    						} catch (BadPaddingException e) {
    							e.printStackTrace();
    						}
    					} catch (InvalidKeyException e) {
    						e.printStackTrace();
    					}
    				} catch (NoSuchAlgorithmException e) {
    					e.printStackTrace();
    				} catch (NoSuchPaddingException e) {
    					e.printStackTrace();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			} catch (ClassNotFoundException e) {
    				e.printStackTrace();
    			}
    			keyIn.close();
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
     
    	private static String decrypt(String passwordCrypte)
    	{
    		//	déballe de la clé privé RSA
            ObjectInputStream keyIn;
    		try {
    			keyIn = new ObjectInputStream(new FileInputStream("decryptionKey.key"));
    			Key decryptionKey;
    			try {
    				decryptionKey = (Key)keyIn.readObject();
    				Cipher rsa;
    				try {
    					rsa = Cipher.getInstance("RSA");
    					try {
    						rsa.init(Cipher.DECRYPT_MODE, decryptionKey);
    						//	Decode base64 to get bytes
    				        byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(passwordCrypte);
     
    				        // Decrypt
    				        byte[] utf8 = rsa.doFinal(dec);
    				        // Decode using utf-8
    				        return new String(utf8, "UTF8");
     
    					} catch (InvalidKeyException e) {
    						e.printStackTrace();
    					} catch (IllegalBlockSizeException e) {
    						e.printStackTrace();
    					} catch (BadPaddingException e) {
    						e.printStackTrace();
    					}
    				} catch (NoSuchAlgorithmException e) {
    					e.printStackTrace();
    				} catch (NoSuchPaddingException e) {
    					e.printStackTrace();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			} catch (ClassNotFoundException e) {
    				e.printStackTrace();
    			}
    			keyIn.close();
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    }
    Si vous avez des suggestions pour améliorer tout ca, je suis preneur.

    aswat

  11. #11
    Membre éclairé Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut
    Pour info, voivi la classe d'encryption RSA bien faite.


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
     
    /*
     * RSAEncryptor.java
     *
     * Created on 17 juin 2006, 15:58
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */
     
    package org.umh.crypto;
     
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.security.GeneralSecurityException;
    import java.security.InvalidKeyException;
    import java.security.InvalidParameterException;
    import java.security.Key;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.SecureRandom;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.ShortBufferException;
    import javax.crypto.BadPaddingException;
     
    /**
     * This class provides methods for generate keys, encrypt or decrypt files and
     * streams with the RSA crypting algorithm.
     * @author Absil Romain
     */
    public class RSAEncryptor implements CipherEncryptor
    {
        private Key publicKey;
        private Key privateKey;
        private boolean isEncryptInitialized;
        private boolean isDecryptInitialized;
     
        /**
         * Constructs a new RSA encryptor with the specified file containing one 
         * of the keys, in encrypt or decrypt mode (depends on the type of stored
         * key, if the key is public, then the encryptor is in encrypt mode,
         * otherwise it is in decrypt mode.
         * @param keyFileName the name of the file containing a RSA key.
         * @throws java.io.FileNotFoundException if the file containing the key doesn't
         * exist.
         * @throws java.io.IOException if an error occurs during reading the file 
         * containing the key.
         * @throws java.lang.ClassNotFoundException if the class of the key is unknown.
         * @throws java.security.InvalidKeyException is the stored key is not a valid type of key.
         */
        public RSAEncryptor(String keyFileName) 
            throws FileNotFoundException, IOException, ClassNotFoundException, 
                InvalidKeyException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(keyFileName));
            Object key = keyIn.readObject();
            keyIn.close();
     
            if(key instanceof PublicKey)
            {
                publicKey = (Key)key;
                isEncryptInitialized = true;
            }
            else if(key instanceof PrivateKey)
            {
                privateKey = (Key)key;
                isDecryptInitialized = true;
            }
            else
                throw new InvalidKeyException("The file does not contain a " +
                        "valid key");
        }
     
        /**
         * Constructs a new RSA encryptor with the specified file containing one 
         * of the keys, in encrypt or decrypt mode (depends on the type of stored
         * key, if the key is public, then the encryptor is in encrypt mode,
         * otherwise it is in decrypt mode.
         * @param keyFile the file containing a RSA key.
         * @throws java.io.FileNotFoundException if the file containing the key doesn't
         * exist.
         * @throws java.io.IOException if an error occurs during reading the file 
         * containing the key.
         * @throws java.lang.ClassNotFoundException if the class of the key is unknown.
         * @throws java.security.InvalidKeyException is the stored key is not a valid type of key.
         */
        public RSAEncryptor(File keyFile) 
            throws FileNotFoundException, IOException, ClassNotFoundException, InvalidKeyException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(keyFile));
            Object key = keyIn.readObject();
            keyIn.close();
     
            if(key instanceof PublicKey)
            {
                publicKey = (Key)key;
                isEncryptInitialized = true;
            }
            else if(key instanceof PrivateKey)
            {
                privateKey = (Key)key;
                isDecryptInitialized = true;
            }
            else
                throw new InvalidKeyException("The file does not contain a " +
                        "valid key");
        }
     
        /**
         * Constructs a new RSA encryptor in encrypt mode with the specified
         * public key.
         * @param key the public key (used to encrypt files and streams).
         **/
        public RSAEncryptor(PublicKey key)
        {
            this.publicKey = key;
            this.isEncryptInitialized = true;
        }
     
        /**
         * Constructs a new RSA encryptor in decrypt mode with the specified
         * private key.
         * @param key the private key (used to decrypt files and streams).
         **/
        public RSAEncryptor(PrivateKey key)
        {
            this.privateKey = key;
            this.isDecryptInitialized = true;
        }
     
        /**
         * Constructs a new RSA encryptor in encrypt and decrypt mode with the
         * specified files containing the public and private key.
         * @param publicKeyFileName the name of the file containing the public key.
         * @param privateKeyFileName the name of the file containing the private key.
         * @throws java.io.FileNotFoundException if one of the files containing a key 
         * doen't exist.
         * @throws java.io.IOException if an error occurs during reading one of the keys.
         * @throws java.lang.ClassNotFoundException if one of the class of the keys is
         * unknown.
         * @throws java.security.InvalidKeyException if the files containing the keys don't
         * contain valid keys.
         */
        public RSAEncryptor(String publicKeyFileName, String privateKeyFileName) 
            throws FileNotFoundException, IOException, ClassNotFoundException,
                InvalidKeyException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicKeyFileName));
            Object puKey = keyIn.readObject();
            keyIn.close();
     
            keyIn = new ObjectInputStream(
                    new FileInputStream(privateKeyFileName));
            Object prKey = keyIn.readObject();
            keyIn.close();
     
            if(puKey instanceof PublicKey && prKey instanceof PrivateKey)
            {
                this.publicKey = (Key)puKey;
                this.isEncryptInitialized = true;
                this.privateKey = (Key)prKey;
                this.isDecryptInitialized = true;
            }
            else
                throw new InvalidKeyException("Some of the files don't contains" +
                        " a valid key");
        }
     
        /**
         * Constructs a new RSA encryptor in encrypt and decrypt mode with the
         * specified files containing the public and private key.
         * @param publicKeyFile the file containing the public key.
         * @param privateKeyFile the file containing the private key.
         * @throws java.io.FileNotFoundException if one of the files containing a key 
         * doen't exist.
         * @throws java.io.IOException if an error occurs during reading one of the keys.
         * @throws java.lang.ClassNotFoundException if one of the class of the keys is
         * unknown.
         */
        public RSAEncryptor(File publicKeyFile, File privateKeyFile) 
            throws FileNotFoundException, IOException, ClassNotFoundException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicKeyFile));
            this.publicKey = (Key) keyIn.readObject();
            this.isEncryptInitialized = true;
            keyIn.close();
     
            keyIn = new ObjectInputStream(
                    new FileInputStream(privateKeyFile));
            this.privateKey = (Key) keyIn.readObject();
            this.isDecryptInitialized = true;
            keyIn.close();
        }
     
        /**
         * Construct a new RSA encryptor in encrypt and decrypt mode with the
         * specified public and private key.
         * @param publicKey the public key (used to encrypt files and streams).
         * @param privateKey the private key (used to decrypt files and streams).
         **/
        public RSAEncryptor(PublicKey publicKey, PrivateKey privateKey)
        {
            this.publicKey = publicKey;
            this.isEncryptInitialized = true;
            this.privateKey = privateKey;
            this.isDecryptInitialized = true;
        }
     
        /**
         * Construct a new RSA encryptor in encrypt and decrypt mode with the
         * specified pair of keys.
         * @param keyPair the pair of keys used to encrypt and decrypt files and
         * streams.
         **/
        public RSAEncryptor(KeyPair keyPair)
        {
            this(keyPair.getPublic(), keyPair.getPrivate());
        }
     
        /**
         * Returns the public key of the underlying encryptor.
         * @return the public key of the underlying encryptor.
         **/
        public PublicKey getPublicKey()
        {
            return (PublicKey) publicKey;
        }
     
        /**
         * Sets the public key of the underlying encryptor.
         * @param key the public key to set.
         **/
        public void setPublicKey(PublicKey key)
        {
            this.publicKey = key;
        }
     
        /**
         * Returns the private key of the underlying encryptor.
         * @return the private key of the underlying encryptor.
         **/
        public PrivateKey getPrivateKey()
        {
            return (PrivateKey) privateKey;
        }
     
        /**
         * Returns a new instance of RSAEncryptor with the specified size for
         * generated keys.
         * @param size the size of the generated keys.
         * @return a new instance of RSAEncryptor.
         **/
        public static RSAEncryptor getInstance(int size)
        {
            return new RSAEncryptor(generateKeys(size));
        }
     
        /**
         * Returns a new instance of RSAEncryptor with the specified size for
         * generated keys and writes them into the specified files.
         * @return a new instance of RSAEncryptor.
         * @param size the size of the generated keys.
         * @param publicKeyFileName the name of the file in wich youw ant to write
         * the public key.
         * @param privateKeyFileName the name of the file in wich youw ant to write
         * the private key.
         * @throws java.io.IOException if an error occurs during writing one of the keys.
         */
        public static RSAEncryptor getInstance(int size, String publicKeyFileName,
                String privateKeyFileName) throws IOException
        {
            return new RSAEncryptor(generateAndSaveKeys(size, publicKeyFileName, privateKeyFileName));
        }
     
        /**
         * Returns a new instance of RSAEncryptor with the specified size for
         * generated keys and writes them into the specified files.
         * @return a new instance of RSAEncryptor.
         * @param size the size of the generated keys.
         * @param publicKeyFile the file in wich youw ant to write the public key.
         * @param privateKeyFile the file in wich youw ant to write the private key.
         * @throws java.io.IOException if an error occurs during writing one of the keys.
         */
        public static RSAEncryptor getInstance(int size, File publicKeyFile, 
                File privateKeyFile) throws IOException
        {
            return new RSAEncryptor(generateAndSaveKeys(size, publicKeyFile, privateKeyFile));
        }
     
        /**
         * Returns a pair of keys generated with the specified size.
         * @return a pair of keys generated with the specified size.
         * @param size the size of the generated key.
         */
        public static KeyPair generateKeys(int size)
        {
            KeyPairGenerator pairgen = null;
            try
            {
                pairgen = KeyPairGenerator.getInstance("RSA");
            } 
            catch (NoSuchAlgorithmException ex)//never launched
            {
                ex.printStackTrace();
            }
            SecureRandom random = new SecureRandom();
            pairgen.initialize(size, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            return keyPair;
        }
     
        /**
         * Returns a pair of keys generated with the specified size and writes 
         * them into the specified files.
         * @param size the size of the generated keys.
         * @param publicKeyFileName the name of the file in wich youw ant to write
         * the public key.
         * @param privateKeyFileName the name of the file in wich youw ant to write
         * the private key.
         * @return a pair of keys with the specified size.
         * @throws java.io.IOException if an error occurs during writing the keys.
         **/
        public static KeyPair generateAndSaveKeys(int size, String publicKeyFileName, 
                String privateKeyFileName) throws IOException
        {
            KeyPair keyPair = generateKeys(size);
     
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(publicKeyFileName));
            out.writeObject(keyPair.getPublic());
            out.close();
     
            out = new ObjectOutputStream(
                    new FileOutputStream(privateKeyFileName));
            out.writeObject(keyPair.getPrivate());
            out.close();
     
            return keyPair;
        }
     
        /**
         * Returns a pair of keys generated with the specified size and writes 
         * them into the specified files.
         * @param size the size of the generated keys.
         * @param publicKeyFile the file in wich you want to write the public key.
         * @param privateKeyFile the file in wich you want to write the private key.
         * @return a pair of keys with the specified size.
         * @throws java.io.IOException if an error occurs during writing the keys.
         **/
        public static KeyPair generateAndSaveKeys(int size, File publicKeyFile, 
                File privateKeyFile) throws IOException
        {
            KeyPair keyPair = generateKeys(size);
     
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(publicKeyFile));
            out.writeObject(keyPair.getPublic());
            out.close();
     
            out = new ObjectOutputStream(
                    new FileOutputStream(privateKeyFile));
            out.writeObject(keyPair.getPrivate());
            out.close();
     
            return keyPair;
        }
    La suite au prochain post(sinon ça plante...)

  12. #12
    Membre éclairé Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut
    La suite donc :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
     
     
    /**
         * Encrypts the specified input file to the specified output file.
         * @param inputFileName the name of the file to encrypt.
         * @param outputFileName the name of the file where you want to write 
         * the encrypted file.
         * @throws java.io.FileNotFoundException if the file to encrypt doesn't
         * exist.
         * @throws java.io.IOException if an error occurs during writing encrypted
         * datas.
         * @throws java.security.InvalidKeyException if the key is not valid for
         * this type of operation.
         * @throws javax.crypto.IllegalBlockSizeException if the cipher is a block
         * cipher, no padding has been requested, and the length of the encoding
         * of the key to be wrapped is not a multiple of the block size.
         */
        public void encryptFile(String inputFileName, String outputFileName) 
            throws InvalidKeyException, IllegalBlockSizeException, 
                FileNotFoundException, IOException
        {
            if(!this.isEncryptInitialized)
                throw new IllegalStateException("The underlying encryptor is not" +
                        " initialized in encrypt mode. You must specify a " +
                        "public key.");
            KeyGenerator keygen = null;
            Cipher cipherRsa = null;
            Cipher cipherAes= null;
            try
            {
                keygen = KeyGenerator.getInstance("AES");
                cipherRsa = Cipher.getInstance("RSA");
                cipherAes = Cipher.getInstance("AES");
            }
            catch(NoSuchAlgorithmException e)//never launched
            {
                e.printStackTrace();
            }
            catch(NoSuchPaddingException e)
            {
                e.printStackTrace();
            }
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();
     
            cipherRsa.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = cipherRsa.wrap(key);
            DataOutputStream out = new DataOutputStream(
                    new FileOutputStream(outputFileName));
            out.writeInt(wrappedKey.length);
            out.write(wrappedKey);
     
            InputStream in = new FileInputStream(inputFileName);
     
            cipherAes.init(Cipher.ENCRYPT_MODE, key);
            crypt(in, out, cipherAes);
            in.close();
            out.close();
        }
     
        /**
         * Encrypts the specified input file to the specified output file.
         * @param inputFile file to encrypt.
         * @param outputFile the file where you want to write the encrypted file.
         * @throws java.io.FileNotFoundException if the file to encrypt doesn't
         * exist.
         * @throws java.io.IOException if an error occurs during writing encrypted
         * datas.
         * @throws java.security.InvalidKeyException if the key is not valid for
         * this type of operation.
         * @throws javax.crypto.IllegalBlockSizeException if the cipher is a block
         * cipher, no padding has been requested, and the length of the encoding
         * of the key to be wrapped is not a multiple of the block size.
         */
        public void encryptFile(File inputFile, File outputFile)
            throws InvalidKeyException, IllegalBlockSizeException, 
                FileNotFoundException, IOException
        {
            if(!this.isEncryptInitialized)
                throw new IllegalStateException("The underlying encryptor is not" +
                        " initialized in encrypt mode. You must specify a " +
                        "public key.");
            KeyGenerator keygen = null;
            Cipher cipherRsa = null;
            Cipher cipherAes= null;
            try
            {
                keygen = KeyGenerator.getInstance("AES");
                cipherRsa = Cipher.getInstance("RSA");
                cipherAes = Cipher.getInstance("AES");
            }
            catch(NoSuchAlgorithmException e)//never launched
            {
                e.printStackTrace();
            }
            catch(NoSuchPaddingException e)
            {
                e.printStackTrace();
            }
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();
     
            cipherRsa.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = cipherRsa.wrap(key);
            DataOutputStream out = new DataOutputStream(
                    new FileOutputStream(outputFile));
            out.writeInt(wrappedKey.length);
            out.write(wrappedKey);
     
            InputStream in = new FileInputStream(inputFile);
     
            cipherAes.init(Cipher.ENCRYPT_MODE, key);
            crypt(in, out, cipherAes);
            in.close();
            out.close();
        }
     
        /**
         * Decrypts the specified input file to the specified output file.
         * @param inputFileName the name of the file to decrypt.
         * @param outputFileName the name of the file where you want to write 
         * the decrypted file.
         * @throws java.io.FileNotFoundException if the file to decrypt doesn't
         * exist.
         * @throws java.io.IOException if an error occurs during writing decrypted
         * datas.
         * @throws java.security.InvalidKeyException if the key is not valid for
         * this type of operation.
         */
        public void decryptFile(String inputFileName, String outputFileName) 
            throws FileNotFoundException, IOException, InvalidKeyException
        {
            if(!this.isEncryptInitialized)
                throw new IllegalStateException("The underlying encryptor is not" +
                        " initialized in decrypt mode. You must specify a " +
                        "private key.");
            DataInputStream in = new DataInputStream(
                    new FileInputStream(inputFileName));
            int length = in.readInt();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);
            Cipher cipherRsa = null;
            Cipher cipherAes = null;
            Key key = null;
            try
            {
                cipherRsa = Cipher.getInstance("RSA");
                cipherAes = Cipher.getInstance("AES");
                cipherRsa.init(Cipher.UNWRAP_MODE, privateKey); 
                key = cipherRsa.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
            }
            catch(NoSuchAlgorithmException e)//never thrown
            {
                e.printStackTrace();
            }
            catch(NoSuchPaddingException e)//never thrown
            {
                e.printStackTrace();
            }
     
            OutputStream out = new FileOutputStream(outputFileName);
            cipherAes.init(Cipher.DECRYPT_MODE, key);
     
            crypt(in, out, cipherAes);
            in.close();
            out.close();
        }
     
        /**
         * Decrypts the specified input file to the specified output file.
         * @param inputFile the file to decrypt.
         * @param outputFile the file where you want to write the decrypted file.
         * @throws java.io.FileNotFoundException if the file to decrypt doesn't
         * exist.
         * @throws java.io.IOException if an error occurs during writing decrypted
         * datas.
         * @throws java.security.InvalidKeyException if the key is not valid for
         * this type of operation.
         */
        public void decryptFile(File inputFile, File outputFile)
            throws FileNotFoundException, IOException, InvalidKeyException
        {
            if(!this.isEncryptInitialized)
                throw new IllegalStateException("The underlying encryptor is not" +
                        " initialized in decrypt mode. You must specify a " +
                        "private key.");
            DataInputStream in = new DataInputStream(
                    new FileInputStream(inputFile));
            int length = in.readInt();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);
            Cipher cipherRsa = null;
            Cipher cipherAes = null;
            Key key = null;
            try
            {
                cipherRsa = Cipher.getInstance("RSA");
                cipherAes = Cipher.getInstance("AES");
                cipherRsa.init(Cipher.UNWRAP_MODE, privateKey); 
                key = cipherRsa.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
            }
            catch(NoSuchAlgorithmException e)//never thrown
            {
                e.printStackTrace();
            }
            catch(NoSuchPaddingException e)//never thrown
            {
                e.printStackTrace();
            }
     
            OutputStream out = new FileOutputStream(outputFile);
            cipherAes.init(Cipher.DECRYPT_MODE, key);
     
            crypt(in, out, cipherAes);
            in.close();
            out.close();
        }
     
        /**
         * Encrypts the specified input stream to the specified output stream.
         * @param in the stream to encrypt.
         * @param out the stream where you want to write the encrypted stream.
         * @throws java.io.IOException if an error occurs during writing encrypted
         * datas.
         * @throws java.security.InvalidKeyException if the key is not valid for
         * this type of operation.
         * @throws javax.crypto.IllegalBlockSizeException if the cipher is a block
         * cipher, no padding has been requested, and the length of the encoding
         * of the key to be wrapped is not a multiple of the block size.
         */
        public void encryptStream(InputStream in, OutputStream out) 
            throws InvalidKeyException, IllegalBlockSizeException, IOException
        {
            if(!this.isEncryptInitialized)
                throw new IllegalStateException("The underlying encryptor is not" +
                        " initialized in encrypt mode. You must specify a " +
                        "public key.");
            KeyGenerator keygen = null;
            Cipher cipherRsa = null;
            Cipher cipherAes= null;
            try
            {
                keygen = KeyGenerator.getInstance("AES");
                cipherRsa = Cipher.getInstance("RSA");
                cipherAes = Cipher.getInstance("AES");
            }
            catch(NoSuchAlgorithmException e)//never launched
            {
                e.printStackTrace();
            }
            catch(NoSuchPaddingException e)
            {
                e.printStackTrace();
            }
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();
     
            cipherRsa.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = cipherRsa.wrap(key);
     
            Integer length = wrappedKey.length;
            out.write(length.byteValue());
            out.write(wrappedKey);
     
            cipherAes.init(Cipher.ENCRYPT_MODE, key);
            crypt(in, out, cipherAes);
            in.close();
            out.close();
        }
     
        /**
         * Decrypts the specified input stream to the specified output stream.
         * @param in the stream to decrypt.
         * @param out the stream where you want to write the decrypted stream.
         * @throws java.io.IOException if an error occurs during writing encrypted
         * datas.
         * @throws java.security.InvalidKeyException if the key is not valid for
         * this type of operation.
         */
        public void decryptStream(InputStream in, OutputStream out) 
            throws IOException, InvalidKeyException
        {
            if(!this.isEncryptInitialized)
                throw new IllegalStateException("The underlying encryptor is not" +
                        " initialized in decrypt mode. You must specify a " +
                        "private key.");
            int length = in.read();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);
            Cipher cipherRsa = null;
            Cipher cipherAes = null;
            Key key = null;
            try
            {
                cipherRsa = Cipher.getInstance("RSA");
                cipherAes = Cipher.getInstance("AES");
                cipherRsa.init(Cipher.UNWRAP_MODE, privateKey); 
                key = cipherRsa.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
            }
            catch(NoSuchAlgorithmException e)//never thrown
            {
                e.printStackTrace();
            }
            catch(NoSuchPaddingException e)
            {
                e.printStackTrace();
            }
     
            cipherAes.init(Cipher.DECRYPT_MODE, key);
     
            crypt(in, out, cipherAes);
            in.close();
            out.close();
        }
     
        /**
         * Crypts or decrypts the specified input stream to the specified output
         * stream with a given cipher. The crypting or decrypting operation is 
         * determined by the cipher's state.
         * @param cipher the cipher used to crypt datas.
         * @param in the input srteal stream to be encypted or decrypted.
         * @param out the output stream to be encypted or decrypted.
         * @throws java.io.IOException if an I/O error occurs during reading 
         * the input stream or writting datas to the output stream.
         */
        public void crypt(InputStream in, OutputStream out, Cipher cipher)
            throws IOException
        {
            int blockSize = cipher.getBlockSize();
            int outputSize = cipher.getOutputSize(blockSize);
            byte[] inBytes = new byte[blockSize];
            byte[] outBytes = new byte[outputSize];
     
            int inLength = 0;
            boolean done = false;
            while(!done)
            {
                inLength = in.read(inBytes);
                if(inLength == blockSize)
                {
                    try
                    {
                        int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
                        out.write(outBytes, 0, outLength);
                    }
                    catch(ShortBufferException e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                    done = true;
            }
     
            try
            {
                if(inLength > 0)
                    outBytes = cipher.doFinal(inBytes, 0, inLength);
                else
                    outBytes = cipher.doFinal();
                out.write(outBytes);
            }
            catch(IllegalBlockSizeException e)
            {
                e.printStackTrace();
            }
            catch(BadPaddingException e)
            {
                e.printStackTrace();
            }
        }
    }

    Et voilà fini.
    Amuse-toi bien

  13. #13
    Membre éclairé Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut
    J'avais besoin comme toi de crypter des String sans devoir les écrire, mais ça ne marche pas.

    J'ai ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes
            at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
            at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
            at javax.crypto.Cipher.doFinal(DashoA13*..)
    ...
    Il faut passer par cipher.update et passer de petits blocs de bytes, mais le truc c'est que cipher.getBockSize() vaut zéro... Comment as-tu fait?

Discussions similaires

  1. Cryptage / decryptage xor
    Par deny dans le forum Débuter
    Réponses: 2
    Dernier message: 08/06/2008, 11h52
  2. Problème Cryptage / Decryptage
    Par Invité dans le forum C#
    Réponses: 6
    Dernier message: 19/05/2008, 16h51
  3. cryptage/decryptage, comment faire?
    Par bossun dans le forum Général Dotnet
    Réponses: 6
    Dernier message: 24/04/2008, 17h07
  4. Cryptage Decryptage asymetrique
    Par bslota dans le forum Sécurité
    Réponses: 5
    Dernier message: 02/05/2007, 16h15
  5. [VB]Cryptage/decryptage
    Par Tyrael62 dans le forum VB 6 et antérieur
    Réponses: 14
    Dernier message: 25/01/2006, 18h57

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo