简体   繁体   中英

Create a file protected by a password in java

I would like to create a file protected by a password in JAVA. What I mean is, once I launch the program, one file created by my program would be directly protected by previously determined password.

Is there an easy way to do it ?

Once again, my aim is not to create a file and then add it a password, but right during the creation protecting the file by a password. Actually, I want the current runner program not having access in reading/editing the created file EXCEPT if he/she has the password previously set.

So anyway, if some of you know an easy way to protect files when writing them thanks to java, I would be most grateful.

Have a nice day!

You want to encrypt your file('s content) with a password. Here is a pretty well known library to do it: http://www.jasypt.org/

From their site:

..encrypting and decrypting a text...

BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword(myEncryptionPassword);
String myEncryptedText = textEncryptor.encrypt(myText);
...
String plainText = textEncryptor.decrypt(myEncryptedText);

You can read/write the encrypted content to your file.

When you want to encrypt files, strings, etc there are 2 main approaches. You should start by building a class or method to convert ur string/file to an array of bytes. Build another method to convert the array of bytes back to the string/file.

You may encrypt a file using 2 approaches: 1 - Symmetric key - A secret word (usually a huge string of chars or a password set by the user) will encrypt your file and password, and the same password will be used to decrypt. 2 - Asymmetric key - You generate a pair of keys. One is called the public key and the other is called a private key. Public keys are used to encrypt files, private keys to decrypt. This would be the more 'professional' approach.

If you want a really safe approach, you should download GnuPG. GnuPG is an executable that manages assymmetric encryption, you may build a class to work with GnuPG and let GnuPG manage ur encryption/decryption process.

Theres an unsafe approach that is 'native' to java (symmetric key) that may work out for you:

Encryption:

byte[] key = //... password converted to an array of bytes
byte[] dataToSend = ...

Cipher c = Cipher.getInstance("AES");
SecretKeySpec k =
  new SecretKeySpec(key, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
byte[] encryptedData = c.doFinal(dataToSend);

Decryption:

byte[] key = //
byte[] encryptedData = //

Cipher c = Cipher.getInstance("AES");
SecretKeySpec k =
  new SecretKeySpec(key, "AES");
c.init(Cipher.DECRYPT_MODE, k);
byte[] data = c.doFinal(encryptedData);

Hope this helps.

If the file is a plain text file, then not giving the user access to the file without a password in your program does not really password-protect the data, because the user can just open the file with some other program. So IF the file is a text file, then I think you must use encryption.

You can use the comment by @mazaneicha to help you get started in this direction. If you want to dive more into it, you can look at the Java Cryptography architectre and the javax.crypto java docs .

If your file is not human-readable, and only your program understands it, then I would make the first line or first n Bytes of the file a password. If you prefer, you could save another password file in the same directory and use that to authenticate the user before deciding if the user has the right to view the file. A common way to encrypt a password is with an MD5 hash function. The user enters a password, you compute the hash of it, then compare the computed hash with the hash value read from the file:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Use to encrypt passwords using MD5 algorithm
 * @param password should be a plain text password.
 * @return a hex String that results from encrypting the given password.
 */
static String encryptPassword(String password) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());
        byte byteData[] = md.digest();
        StringBuilder hexString = new StringBuilder();
        for (int i=0;i<byteData.length;i++) {
            String hex=Integer.toHexString(0xff & byteData[i]);
            if(hex.length()==1) 
               hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
    catch(java.security.NoSuchAlgorithmException missing) {
        return password;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM