Moyen le plus simple de chiffrer un fichier texte en java


Pour mon projet scolaire, j'ai dû montrer que je pouvais utiliser la gestion de fichiers dans un programme. Pour cela, j'ai fait un processus de connexion très simple sur lequel vous pouvez créer un compte qui écrit un nom d'utilisateur et un mot de passe dans un fichier texte situé dans le dossier de ressources. Évidemment, cela n'a aucune sécurité car il n'a pas été conçu pour être sécurisé juste pour présenter la gestion des fichiers, mais mon professeur a dit que je devrais essayer d'ajouter un cryptage au fichier pour obtenir une meilleure note.

J'ai fait quelques recherches et beaucoup de gens recommandent DES.

Le problème que j'ai est que je n'ai pas beaucoup de temps pour mon projet et que je dois le terminer dès que possible. L'utilisation de DES semble prendre un certain temps pour implémenter tout le code supplémentaire.

Dans mon programme, j'utilise un simple lineNumberReader pour lire les fichiers ligne par ligne. Pour écrire dans les fichiers, j'utilise un BufferedWriter.

Existe-t-il de toute façon pour crypter ces données très simplement? Il ne doit pas être très sécurisé mais j'en ai besoin montrer que j'ai au moins tenté de chiffrer les données. Le cryptage et le décryptage seraient tous terminés sur la même application car les données ne sont pas transférées.

Potentiellement un moyen de créer moi-même un algorithme de cryptage et de décryptage très simple?

Author: Patch, 2015-01-15

10 answers

Essayez ceci,... C'est assez simple

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class HelloWorld{
    public static void main(String[] args) {

        try{
            KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
            SecretKey myDesKey = keygenerator.generateKey();

            Cipher desCipher;
            desCipher = Cipher.getInstance("DES");


            byte[] text = "No body can see me.".getBytes("UTF8");


            desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
            byte[] textEncrypted = desCipher.doFinal(text);

            String s = new String(textEncrypted);
            System.out.println(s);

            desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
            byte[] textDecrypted = desCipher.doFinal(textEncrypted);

            s = new String(textDecrypted);
            System.out.println(s);
        }catch(Exception e)
        {
            System.out.println("Exception");
        }
    }
}

Donc, avant d'écrire dans un fichier, vous crypterez et après avoir lu, vous devrez le déchiffrer.

 23
Author: j4rey, 2015-01-15 11:41:49

Vous pouvez utiliser un simple césar de chiffrement (http://en.wikipedia.org/wiki/Caesar_cipher)

public class Cipher {
public static void main(String[] args) {

    String str = "The quick brown fox Jumped over the lazy Dog";

    System.out.println( Cipher.encode( str, 12 ));
    System.out.println( Cipher.decode( Cipher.encode( str, 12), 12 ));
}

public static String decode(String enc, int offset) {
    return encode(enc, 26-offset);
}

public static String encode(String enc, int offset) {
    offset = offset % 26 + 26;
    StringBuilder encoded = new StringBuilder();
    for (char i : enc.toCharArray()) {
        if (Character.isLetter(i)) {
            if (Character.isUpperCase(i)) {
                encoded.append((char) ('A' + (i - 'A' + offset) % 26 ));
            } else {
                encoded.append((char) ('a' + (i - 'a' + offset) % 26 ));
            }
        } else {
            encoded.append(i);
        }
    }
    return encoded.toString();
}
}

Trouvé à http://rosettacode.org/wiki/Caesar_cipher#Java

Notez que Java a des solutions natives pour le cryptage et quand il s'agit de mots de passe, il est préférable de simplement les hacher et de comparer les hachages car il n'est généralement pas nécessaire de les déchiffrer.

 2
Author: flo, 2015-01-15 11:19:41

Une méthode très basique serait de xor les données avec une clé. Cette méthode est symétrique, c'est-à-dire que vous pouvez utiliser la même clé pour décoder que encoder.

Si on choisit une clé de 1 octet c'est sympa et simple, assez pour la rendre illisible (mais pas du tout sécurisée!):

private void encodeDecode(byte[] bytes, byte key) {
    for(int i=0; i<bytes.length; i++)
        bytes[i] = (byte) (bytes[i]^key);
}
 2
Author: weston, 2015-01-15 11:29:58

Un algorithme de brouillage facile et amusant serait la Burrows-Wheeler transform. Pas vraiment un cryptage sécurisé, mais sérieusement, c'est un travail à l'école et c'est génial.

 1
Author: Olavi Mustanoja, 2015-01-15 11:20:12

Utilisez un algorithme de chiffrement simple, changez chaque caractère en nombre ou autre caractère.

  1. obtenez chaque caractère de votre chaîne.
  2. récupère la valeur ascii de la chaîne.
  3. ajoutez la valeur ascii avec un entier spécifique (ce sera votre clé de chiffrement)
  4. afficher le résultat
 1
Author: pupil, 2015-01-15 11:21:53

Je ne sais pas qui recommande DES pour crypter le mot de passe. Je vous suggère de suivre ces étapes si vous souhaitez impressionner votre professeur:

Cette solution rend votre projet réel et vous pouvez réutiliser pour passer l'examen de votre futur Module Crypto :) . Sinon, j'aime la solution proposée par StanislavL.

Profitez-en!

 0
Author: Aris2World, 2015-01-15 12:00:48

Bouncy Castle Crypto API est une API de cryptographie légère en Java.

    import org.bouncycastle.crypto.*;
    import org.bouncycastle.crypto.engines.*;
    import org.bouncycastle.crypto.modes.*;
    import org.bouncycastle.crypto.params.*;

    // A simple example that uses the Bouncy Castle
    // lightweight cryptography API to perform DES
    // encryption of arbitrary data.


     public class Encryptor {

            private BufferedBlockCipher cipher;
            private KeyParameter key;


            // Initialize the cryptographic engine.
            // The key array should be at least 8 bytes long.


            public Encryptor( byte[] key ){
            /*
            cipher = new PaddedBlockCipher(
                       new CBCBlockCipher(new DESEngine()));
            */
            cipher = new PaddedBlockCipher(
                        new CBCBlockCipher(new BlowfishEngine()));
            this.key = new KeyParameter( key );
            }        

            // Initialize the cryptographic engine.
            // The string should be at least 8 chars long.

            public Encryptor( String key ){
            this( key.getBytes());
            }
            // Private routine that does the gritty work.

            private byte[] callCipher( byte[] data )
            throws CryptoException {
            int    size = cipher.getOutputSize( data.length );

            byte[] result = new byte[ size ];
            int    olen = cipher.processBytes(data,0,data.length result, 0);
                   olen += cipher.doFinal( result, olen );

            if( olen < size ){
                byte[] tmp = new byte[ olen ];
                System.arraycopy(
                        result, 0, tmp, 0, olen );
                result = tmp;
            }

            return result;
        }
        // Encrypt arbitrary byte array, returning the
        // encrypted data in a different byte array.

        public synchronized byte[] encrypt( byte[] data )
        throws CryptoException {
            if( data == null || data.length == 0 ){
                return new byte[0];
            }

            cipher.init( true, key );
            return callCipher( data );
        }
       // Encrypts a string.

        public byte[] encryptString( String data )
        throws CryptoException {
            if( data == null || data.length() == 0 ){
                return new byte[0];
            }

            return encrypt( data.getBytes() );
        }
        // Decrypts arbitrary data.

        public synchronized byte[] decrypt( byte[] data )
        throws CryptoException {
            if( data == null || data.length == 0 ){
                return new byte[0];
            }

            cipher.init( false, key );
            return callCipher( data );
        }
        // Decrypts a string that was previously encoded
        // using encryptString.

        public String decryptString( byte[] data )
        throws CryptoException {
            if( data == null || data.length == 0 ){
                return "";
            }

            return new String( decrypt( data ) );
        }
    }
 0
Author: Sanjay Kumar, 2015-01-22 15:44:02

Il y a trop de façons de chiffrer une chaîne simple en Java. S'il s'agit d'un projet scolaire , je ne pense vraiment pas que vous puissiez obtenir une bande plus élevée en utilisant simplement des bibliothèques de troisième partie pour terminer le travail chiffré.

Si vous avez un peu de temps, vous pouvez essayer de comprendre comment fonctionne Base64, puis essayer de créer un algorithme chiffré par vous-même.

Cependant, si vous insistez pour utiliser une API en Java, je dois dire que DES est vraiment une ancienne façon de chiffrer le texte, 3DEs (DESede) ou AES le sera mieux et plus sûr, les deux ont déjà été pris en charge depuis Java6.

Si vous devez importer la lib BouncyCastle , je préfère IDEA, c'est l'un des algorithmes les plus sûrs, peut-être que vous obtenez un bon score.

Je ne vous donnerai aucun code de démonstration, mais vous pouvez facilement en trouver par Google tout l'algorithme que j'ai mentionné.

 0
Author: Bruce_Van, 2015-01-23 03:45:31

Ma suggestion: n'utilisez pas du tout le cryptage. Voici quelque chose de mieux: (J'espère)

Scanner sc=new Scanner(System.in);
String name=sc.next();
//for inputting user name
File f= new File("d://"+name+".txt");
if(f.exists())
{
if(f.lastModified()!=0)
{ 
System.out.println("Account data tampered...cannot be accessed"); 
}
else{
String data="";
System.out.println(data); //data should contain 
//data from file read using BufferedReader
f.setLastModified(0);
}
}
else
{
f.createNewFile();//Write whatever you want to to the file 
f.setLastModified(0);
}

Ainsi, vous pouvez savoir efficacement si l'utilisateur a falsifié le fichier texte avec les détails et afficher un message d'erreur si le compte falsifié est utilisé. Cependant, cela n'empêche pas l'utilisateur de modifier le fichier, cela empêchera simplement l'utilisation d'un compte falsifié....Je pense que votre professeur d'informatique pourrait aimer ça. Vous pourriez aussi faire: f.setReadOnly(); et quand vous écrivez au fichier, f.setWritable(true,true), puis après avoir fermé le flux de sortie, f.setReadOnly(); Encore une fois... Mais le fichier peut toujours être remplacé, donc le 1er et le plus Efficace. Merci

 -1
Author: Nikhil Narayanan, 2018-07-08 16:36:22
public class CryptoUtils {

    public static void encrypt(String key, File inputFile, File outputFile)
            throws CryptoException {
        doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
    }

    public static void decrypt(String key, File inputFile, File outputFile)
            throws CryptoException {
        doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
    }

    private static void doCrypto(int cipherMode, String key, File inputFile,
            File outputFile) throws CryptoException {
        try {
            Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(cipherMode, secretKey);

            FileInputStream inputStream = new FileInputStream(inputFile);
            byte[] inputBytes = new byte[(int) inputFile.length()];
            inputStream.read(inputBytes);

            byte[] outputBytes = cipher.doFinal(inputBytes);

            FileOutputStream outputStream = new FileOutputStream(outputFile);
            outputStream.write(outputBytes);

            inputStream.close();
            outputStream.close();

        } catch (NoSuchPaddingException | NoSuchAlgorithmException
                | InvalidKeyException | BadPaddingException
                | IllegalBlockSizeException | IOException ex) {
            throw new CryptoException("Error encrypting/decrypting file", ex);
        }
    }
}

package net.codejava.crypto;

import java.io.File;

public class CryptoException extends Exception {

    public CryptoException() {
    }

    public CryptoException(String message, Throwable throwable) {
        super(message, throwable);
    }

    public static void main(String[] args) {
        String key = "Mary has one cat1";
        File inputFile = new File("document.txt");
        File encryptedFile = new File("document.encrypted");
        File decryptedFile = new File("document.decrypted");

        try {
            CryptoUtils.encrypt(key, inputFile, encryptedFile);
            CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
        } catch (CryptoException ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }
}
 -3
Author: IDK, 2017-11-15 16:18:23