Easy way to store/restore encryption key for decrypting string in java

前端 未结 4 1284
梦毁少年i
梦毁少年i 2020-12-23 15:13

For encryption I use something like this:

SecretKey aesKey = KeyGenerator.getInstance(\"AES\").generateKey();
StringEncrypter aesEncrypt = new StringEncrypte         


        
4条回答
  •  情书的邮戳
    2020-12-23 15:52

    I've had to do this myself recently. And while the other answers here led me in the right direction, it could have been easier. So here is my "share" for the day, a couple of helper methods for simple AES key manipulation. (Note the dependency on Apache Commons and Codec.)

    This is all in a git repo now: github.com/stuinzuri/SimpleJavaKeyStore

    import static org.apache.commons.codec.binary.Hex.*;
    import static org.apache.commons.io.FileUtils.*;
    import java.io.*;
    import java.security.NoSuchAlgorithmException;
    import javax.crypto.*;
    import org.apache.commons.codec.DecoderException;
    
    public static SecretKey generateKey() throws NoSuchAlgorithmException
    {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(256); // 128 default; 192 and 256 also possible
        return keyGenerator.generateKey();
    }
    
    public static void saveKey(SecretKey key, File file) throws IOException
    {
        char[] hex = encodeHex(key.getEncoded());
        writeStringToFile(file, String.valueOf(hex));
    }
    
    public static SecretKey loadKey(File file) throws IOException
    {
        String data = new String(readFileToByteArray(file));
        byte[] encoded;
        try {
            encoded = decodeHex(data.toCharArray());
        } catch (DecoderException e) {
            e.printStackTrace();
            return null;
        }
        return new SecretKeySpec(encoded, "AES");
    }
    

提交回复
热议问题