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

Langage Java Discussion :

Cryptage de String


Sujet :

Langage Java

  1. #1
    Membre averti
    Homme Profil pro
    Développeur Java
    Inscrit en
    Avril 2012
    Messages
    41
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Finance

    Informations forums :
    Inscription : Avril 2012
    Messages : 41
    Par défaut Cryptage de String
    Bonjour,
    Je sollicite votre aide pour un programme qui retourne des résultats incorrets.
    Il s'agit d'un code de cryptage d'une chaine de caractère. Les résultats sont !!
    Voici le code:
    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
     
    package cryptagetest;
     
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
     
    public class securite{
     
    private final static String cleSecrete = "Clin";
     
    private final static String algorythme = "RC4";
     
    private final static Key cle = new SecretKeySpec(cleSecrete.getBytes(), algorythme);
     
    public static String text = new String();
     
     
    public static void main(String[] args)
     
    {
     
    String texteCrypte = encrypte(text);
    System.out.println(texteCrypte); //imprime "Äj•y§„ :Õ°Äó"
    String texteEnClair = decrypte(texteCrypte);
    System.out.println(texteEnClair); //imprime "javatropbien"
     
    }
     
     
     
    private static String encrypte(String texteEnClair)
    {
    Cipher cipher = null;
    try
    {
    cipher = Cipher.getInstance(algorythme);
    }
    catch (NoSuchAlgorithmException e) {e.printStackTrace();}
    catch (NoSuchPaddingException e) {e.printStackTrace();}
    try
    {
    cipher.init(Cipher.ENCRYPT_MODE, cle);
    }
    catch (InvalidKeyException e) {e.printStackTrace();}
    byte[] texteCrypte = null;
    try
    {
    texteCrypte = cipher.doFinal(texteEnClair.getBytes());
    }
    catch (IllegalBlockSizeException e) {e.printStackTrace();}
    catch (BadPaddingException e) {e.printStackTrace();}
    return new String(texteCrypte);
    }
     
    private static String decrypte(String texteCrypte)
    {
    Cipher cipher = null;
    try
    {
    cipher = Cipher.getInstance(algorythme);
    }
    catch (NoSuchAlgorithmException e) {e.printStackTrace();}
    catch (NoSuchPaddingException e) {e.printStackTrace();}
    try
    {
    cipher.init(Cipher.DECRYPT_MODE, cle);
    }
    catch (InvalidKeyException e) {e.printStackTrace();}
    byte[] texteEnClair = null;
    try
    {
    texteEnClair = cipher.doFinal(texteCrypte.getBytes());
    }
    catch (IllegalBlockSizeException e) {e.printStackTrace();}
    catch (BadPaddingException e) {e.printStackTrace();}
    return new String(texteEnClair);
    }
    public static void settext(String montext){
        text = montext;
    }
    }

    Alors quelqu'un peut m'aider là dessus??
    Merci beaucoup.

  2. #2
    Modérateur
    Avatar de dinobogan
    Homme Profil pro
    ingénieur
    Inscrit en
    Juin 2007
    Messages
    4 073
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France

    Informations professionnelles :
    Activité : ingénieur
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2007
    Messages : 4 073
    Par défaut
    La chaine est transformée en une suite d'octets non-imprimables.
    ou est le problème ?
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java
    Que la force de la puissance soit avec le courage de ta sagesse.

  3. #3
    Membre averti
    Homme Profil pro
    Développeur Java
    Inscrit en
    Avril 2012
    Messages
    41
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Finance

    Informations forums :
    Inscription : Avril 2012
    Messages : 41
    Par défaut
    comment ça non imprimable??
    à cause du texteEnClair.getBytes() ??
    et pour le décryptage le text original n'est jamais retourné!!

  4. #4
    Membre éclairé
    Profil pro
    Inscrit en
    Mars 2007
    Messages
    333
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2007
    Messages : 333
    Par défaut
    J'ai une belle exception avec ton code. Ta clef n'est pas suffisamment longue.

    Essai ça :


    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
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
     
    public class securite {
     
    	private final static String CLE_SECRETE = "ClinEEE";
     
    	private final static String ALGO = "RC4";
     
    	private final static Key CLE = new SecretKeySpec(CLE_SECRETE.getBytes(),
    			ALGO);
     
    	public static void main(String[] args) {
    		String text = "toto";
    		String texteCrypte = encrypte(text);
    		System.out.println(texteCrypte); // imprime D”·
    		String texteEnClair = decrypte(texteCrypte);
    		System.out.println(texteEnClair); // imprime toto
     
    	}
     
    	private static String encrypte(String texteEnClair) {
    		Cipher cipher = null;
    		try {
    			cipher = Cipher.getInstance(ALGO);
    		} catch (NoSuchAlgorithmException e) {
    			e.printStackTrace();
    		} catch (NoSuchPaddingException e) {
    			e.printStackTrace();
    		}
    		try {
    			cipher.init(Cipher.ENCRYPT_MODE, CLE);
    		} catch (InvalidKeyException e) {
    			e.printStackTrace();
    		}
    		byte[] texteCrypte = null;
    		try {
    			texteCrypte = cipher.doFinal(texteEnClair.getBytes());
    		} catch (IllegalBlockSizeException e) {
    			e.printStackTrace();
    		} catch (BadPaddingException e) {
    			e.printStackTrace();
    		}
    		return new String(texteCrypte);
    	}
     
    	private static String decrypte(String texteCrypte) {
    		Cipher cipher = null;
    		try {
    			cipher = Cipher.getInstance(ALGO);
    		} catch (NoSuchAlgorithmException e) {
    			e.printStackTrace();
    		} catch (NoSuchPaddingException e) {
    			e.printStackTrace();
    		}
    		try {
    			cipher.init(Cipher.DECRYPT_MODE, CLE);
    		} catch (InvalidKeyException e) {
    			e.printStackTrace();
    		}
    		byte[] texteEnClair = null;
    		try {
    			texteEnClair = cipher.doFinal(texteCrypte.getBytes());
    		} catch (IllegalBlockSizeException e) {
    			e.printStackTrace();
    		} catch (BadPaddingException e) {
    			e.printStackTrace();
    		}
    		return new String(texteEnClair);
    	}
     
    }

  5. #5
    Membre averti
    Homme Profil pro
    Développeur Java
    Inscrit en
    Avril 2012
    Messages
    41
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Finance

    Informations forums :
    Inscription : Avril 2012
    Messages : 41
    Par défaut
    Mon output sur netbeans est ça :
    ��k�
    O�<�tO��
    !!!
    le pbm c'est l'affichage en retour qui retourne n'importe quoi!!

  6. #6
    Membre averti
    Homme Profil pro
    Développeur Java
    Inscrit en
    Avril 2012
    Messages
    41
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Finance

    Informations forums :
    Inscription : Avril 2012
    Messages : 41
    Par défaut
    alors j'ai ajouté ceci pour la phase de décryptage et tjrs le mm problème
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    public static String byteEnString(byte[] txt)
    	{
    				return new String(txt);
    	}

  7. #7
    Modérateur

    Profil pro
    Inscrit en
    Septembre 2004
    Messages
    12 582
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 582
    Par défaut
    Citation Envoyé par midou99 Voir le message
    alors j'ai ajouté ceci pour la phase de décryptage et tjrs le mm problème
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    public static String byteEnString(byte[] txt)
    	{
    				return new String(txt);
    	}
    Je vois pas trop comment tu comptais t'en servir.

    Le problème, c'est les octets cryptés : ils ne peuvent pas forcément être transformés en String. Dans ton cas, ils ne peuvent sûrement pas l'être, et tenter de le faire va donner une String avec données corrompues. Une fois que les données sont corrompues, ce n'est plus la peine d'essayer de les décrypter, ça ne marchera pas.

    Il faut garder tes octets cryptés sous forme de byte[]. Il ne faut pas les transformer en String, ou du moins, il ne faut pas garder la String. Genre tu fais println() dessus et ensuite tu l'oublies, tu ne gardes que le byte[] que tu avais.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  8. #8
    Membre Expert Avatar de Uther
    Homme Profil pro
    Tourneur Fraiseur
    Inscrit en
    Avril 2002
    Messages
    4 698
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Pyrénées Orientales (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Tourneur Fraiseur

    Informations forums :
    Inscription : Avril 2002
    Messages : 4 698
    Par défaut
    En effet comme le dit Thelvin, le byte[] doit être conservé tel quel et pas converti directement en chaine de caractère. Ça donne des caractères illisibles et éventuellement des erreurs en fonction de l'encodage utilisé.

    Si tu tiens à avoir une forme cryptée affichable, tu peux convertir le byte[] en chaine de caractère en utilisant le codage base64 par exemple. Tu n'auras pas de mal a trouver une bibliothèque qui fait ça.

  9. #9
    Membre Expert Avatar de Uther
    Homme Profil pro
    Tourneur Fraiseur
    Inscrit en
    Avril 2002
    Messages
    4 698
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Pyrénées Orientales (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Tourneur Fraiseur

    Informations forums :
    Inscription : Avril 2002
    Messages : 4 698
    Par défaut
    En résumé, le problème est le suivant : tu veux convertir en chaine de caractère le byte[] crypté, alors qu'il n'est plus censé représenter une chaine de caractère. Du coup certains caractères sont invalides et perdus.

    Il faut, soit que tu garde le résultats en byte[], ou si tu as absolument besoin d'une chaine affichable, d'utiliser un encodage comme le "Base64" pour convertir le byte[] en String et vice-versa.

    Il y a des bibliothèques comme apache commons codec qui permettent de faire ça simplement.

  10. #10
    Membre très actif
    Profil pro
    Inscrit en
    Février 2010
    Messages
    767
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2010
    Messages : 767
    Par défaut
    Sinon en terme de sécurité, une clé secrète en clair dans le source, autant donner la clé directement, c'est plus que mauvais.

    Et puis ont dit chiffrer et pas crypter, c'est un anglicisme.

    Et enfin on n'utilise plus RC4 comme algorithme : il est considéré comme non sûr depuis que les accès wifi en WEP se casse en une fraction de seconde.

    Bon courage,

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [Lazarus] Passer des strings à un algorithme de cryptage
    Par philgre dans le forum Lazarus
    Réponses: 1
    Dernier message: 11/03/2012, 20h24
  2. cryptage string DES
    Par czezko dans le forum C#
    Réponses: 5
    Dernier message: 23/02/2009, 17h06
  3. RSA Cryptage/Décryptage des String
    Par khaledUSTHB dans le forum VB.NET
    Réponses: 3
    Dernier message: 18/09/2008, 10h49
  4. cryptage query string
    Par debutantasp dans le forum ASP
    Réponses: 8
    Dernier message: 23/05/2008, 19h12
  5. Cryptage/Decryptage de String
    Par aswat dans le forum Sécurité
    Réponses: 12
    Dernier message: 27/08/2007, 16h05

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