java加密解密AES实现

加密时,先用AES加密,再用base64加密;解密时,先用base64解密,再用AES解密。

import org.apache.commons.io.FileUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.io.File;
import java.io.IOException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * Created by fhqplzj on 2017/11/15.
 */
public class AESDemo {
    private static final String algorithm = "AES";

    private static Key getSecretKey() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(47);
            keyGenerator.init(128, secureRandom);
            return keyGenerator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void encrypt(File src_file) {
        try {
            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey());
            byte[] encode_bytes = cipher.doFinal(FileUtils.readFileToByteArray(src_file));

            BASE64Encoder base64Encoder = new BASE64Encoder();
            FileUtils.writeStringToFile(src_file, base64Encoder.encode(encode_bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void decrypt(File src_file) {
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] decode_bytes = base64Decoder.decodeBuffer(FileUtils.readFileToString(src_file));

            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey());
            FileUtils.writeByteArrayToFile(src_file, cipher.doFinal(decode_bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
        File file = new File("/Users/fhqplzj/train.txt");
        decrypt(file);
    }
}


你可能感兴趣的:(java)