安全性—在java中加密文本文件的最简单方法

0ejtzxu1  于 2021-06-30  发布在  Java
关注(0)|答案(11)|浏览(285)

对于我的学校项目,我必须证明我可以在程序中使用文件处理。为此,我做了一个非常简单的登录过程,您可以创建一个帐户,将用户名和密码写入位于资源文件夹中的文本文件。很明显,这没有任何安全性,因为它不是设计为安全只是为了展示文件处理,但我的老师说,我应该尝试添加一些加密文件,以及获得更好的成绩。
我做了一些研究,很多人推荐des。
我的问题是我没有太多的时间留给我的项目,需要尽快完成它。使用des似乎需要一段时间来实现所有额外的代码。
在我的程序中,我使用一个简单的linenumberreader逐行读取文件。要写入文件,我使用的是bufferedwriter。
是否有任何方法可以非常简单地加密这些数据?它不需要非常安全,但我需要证明我至少尝试过加密数据。加密和解密都将在同一个应用程序上完成,因为数据不会被传输。
我可以自己创建一个非常简单的加密和解密算法吗?

nimxete2

nimxete21#

你可以用一个简单的ceasar密码(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();
}
}

发现于http://rosettacode.org/wiki/caesar_cipher#java
请注意,java有用于加密的本机解决方案,当涉及到密码时,只对它们进行散列和比较散列要好得多,因为通常不需要对它们进行解密。

ego6inou

ego6inou2#

bouncy castle crypto api是java中的一个轻量级加密api。

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 ) );
        }
    }
hgncfbus

hgncfbus3#

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();
        }
    }
}
nbysray5

nbysray54#

一个简单有趣的置乱算法是burrows-wheeler变换。不是真正的安全加密,但说真的,这是一个学校的工作,这是可怕的。

8mmmxcuj

8mmmxcuj5#

我不知道谁推荐des加密密码。如果你想给老师留下深刻印象,我建议你遵循以下步骤:
引用您的引用作为加密解决方案的理论支持。我建议给你这个owsap密码存储备忘单
解释代码符合规范的地方。对于一个很好的教程与示例代码,我建议你这个安全的密码哈希
此解决方案使您的项目成为现实,您可以重用它以通过将来加密模块的考试:)。否则我喜欢斯坦尼斯拉夫提出的解决方案。
好好享受!

whitzsjs

whitzsjs6#

在java中加密简单字符串的方法太多了。如果这是一个学校的项目,我真的不认为你可以得到一个更高的波段仅仅使用一些第三方库来完成加密工作。
如果您有时间,可以尝试了解base64的工作原理,然后尝试自己创建一些加密算法。
然而,如果你坚持在java中使用一些api,我不得不说des确实是加密文本的老方法,3des(desede)或aes会更好、更安全,这两种方法从java6开始就已经得到了支持。
如果你必须导入bouncycastle库,我更喜欢这个主意,它是最安全的算法之一,可能会让你取得好成绩。
我不会给你任何演示代码,但你可以很容易地找到一些谷歌所有的算法我已经提到。

mlnl4t2r

mlnl4t2r7#

使用简单的替代加密算法,将每个字符转换成数字或其他字符。
获取字符串的每个字符。
获取字符串的ascii值。
添加带有特定整数的ascii值(这将是您的加密密钥)
显示结果

vql8enpb

vql8enpb8#

我的建议是:不要使用加密。这里有更好的:(我希望)

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);
}

因此,您可以有效地知道用户是否篡改了包含详细信息的文本文件,并在使用被篡改的帐户时显示错误消息。然而,这并不能阻止用户更改文件,它只会阻止被篡改的帐户被使用…我想你的计算机老师可能会喜欢这个。您也可以这样做:f.setreadonly();当您写入文件时,f.setwritable(true,true),然后在关闭输出流后,f.setreadonly();再一次。。。但是文件还是可以替换的,因此第一个和第二个更有效。谢谢

lmyy7pcs

lmyy7pcs9#

可以使用这些函数对简单文本进行加密和解密

//Encrypt simple text
public String EncryptSimpleText (String text2Encrypt) throws Exception {
    byte[] encryptArray = Base64.getEncoder().encode(text2Encrypt.getBytes());
    return new String(encryptArray,"UTF-8");
}

//Decrypt simple text
public String Decrypt2SimpleText(String textEncrypted) throws Exception {
    byte[] dectryptArray = textEncrypted.getBytes();
    byte[] decarray = Base64.getDecoder().decode(dectryptArray);
    return new String(decarray,"UTF-8");
}
kcwpcxri

kcwpcxri10#

试试这个,。。。很简单

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");
        }
    }
}

所以基本上,在写入文件之前,你需要加密,而在读取之后,你需要解密它。

bybem2ql

bybem2ql11#

一个非常基本的方法是用一个键对数据进行异或运算。这种方法是对称的,也就是说,您可以使用相同的密钥进行解码和编码。
如果我们选择一个1字节的密钥,它很好而且简单,足以让它不可读(但一点也不安全!)

private void encodeDecode(byte[] bytes, byte key) {
    for(int i=0; i<bytes.length; i++)
        bytes[i] = (byte) (bytes[i]^key);
}

相关问题