java nio应用 aes字符串加密与解密

阅读更多
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class AESTest {

public static void main(String args[]) {
try {

KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
keygen.init(random);
SecretKey key = keygen.generateKey();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
String str="原始数据";
            System.out.println("加密前数据:"+str);
ByteBuffer in = ByteBuffer.wrap(str.getBytes());
ByteBuffer dec = crypt(in, cipher);
dec.position(0);
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
decrypt(dec, cipher);

} catch (Exception e) {
e.printStackTrace();
}
}

//加密方法
public static ByteBuffer crypt(ByteBuffer in, Cipher cipher)
throws IOException, GeneralSecurityException {
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] outBytes = new byte[outputSize];
in.position(0);
ByteBuffer out = null;

outBytes = cipher.doFinal(in.array());
out = ByteBuffer.wrap(outBytes);

System.out.println("加密数据:" + new String(out.array()));
return out;
}

//解密方法
public static void decrypt(ByteBuffer in, Cipher cipher)
throws IOException, GeneralSecurityException {
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] outBytes = new byte[outputSize];
in.position(0);
ByteBuffer out = null;

outBytes = cipher.doFinal(in.array());
out = ByteBuffer.wrap(outBytes);

System.out.println("解密后数据:" + new String(out.array()));
}

}

你可能感兴趣的:(Java,Security)