在java中加密文本文件的最简单方法

对于我的学校项目,我必须certificate我可以在程序中使用文件处理。 为此,我做了一个非常简单的登录过程,您可以创建一个帐户,将用户名和密码写入资源文件夹中的文本文件。 显然这根本没有安全性,因为它不是为了展示文件处理而设计的,但是我的老师说我应该尝试在文件中添加一些加密以获得更好的成绩。

我做了一些研究,很多人都在推荐DES。

我遇到的问题是我的项目没有太多时间,需要尽快完成。 使用DES似乎需要一段时间来实现所有额外的代码。

在我的程序中,我使用一个简单的lineNumberReader来逐行读取文件。 要写入我正在使用BufferedWriter的文件。

无论如何都要非常简单地加密这些数据吗? 它不一定非常安全,但我需要certificate我至少试图加密数据。 加密和解密都将在同一应用程序上完成,因为数据未被传输。

我可以自己创建一个非常简单的加密和解密算法吗?

试试这个,……非常简单

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

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

您可以使用简单的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具有加密的本机解决方案,当涉及到密码时,最好只散列它们并比较散列,因为通常不需要解密它们。

一个非常基本的方法是用密钥对数据进行xor。 此方法是对称的,即您可以使用相同的密钥进行解码。

如果我们选择一个1字节的密钥,那么它很简单,足以使它不可读(但根本不安全!):

 private void encodeDecode(byte[] bytes, byte key) { for(int i=0; i 

一个简单而有趣的加扰算法是Burrows-Wheeler变换 。 不是真正的安全加密,但严重的是,这是一项学校工作,这太棒了。

使用简单的加密加密算法,将每个字符更改为数字或其他字符。

  1. 得到你的字符串的每个字符。
  2. 获取字符串的ascii值。
  3. 添加具有特定整数的ascii值(这将是您的加密密钥)
  4. 显示结果

我不知道谁建议DES加密密码。 如果您想给老师留下深刻印象,我建议您按照这些步骤操作:

  • 引用您的参考作为对您的加密解决方案的理论支持。 我建议你这个OWSAP – 密码存储备忘单
  • 解释您的代码符合规范的位置。 有关示例代码的好教程,我建议您使用此安全密码哈希

此解决方案使您的项目真实,您可以重复使用它来通过您未来的Crypto模块的考试:)。 否则我喜欢StanislavL提出的解决方案。

请享用!

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

在Java中加密简单字符串的方法太多了。 如果它是一个学校项目,我真的不认为你可以通过简单地使用一些第三方的库来完成加密工作来获得更高的乐队。

如果您有时间,可以尝试了解Base64的工作原理,然后尝试自己创建一些加密算法。

但是,如果你坚持在Java中使用某些API,我不得不说DES是加密文本的老方法,3DE(DESede)或AES会更好更安全,自Java6以来它们都已得到支持。

如果你必须导入BouncyCastle lib,我更喜欢IDEA,它是最安全的算法之一,可能会让你获得好成绩。

我不会给你任何演示代码,但你可以很容易地通过谷歌找到一些我提到的算法。

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

 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(); 再次…但文件仍然可以替换,因此第1和更有效。 谢谢

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