java 加密解密的代码
package endual;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
public class SecretKeyTest {
public static void main(String[] args) throws Exception, NoSuchPaddingException {
String arg0 = "AES"; //加密算法
//加密,密码cipher的意思.加密和解密都是这个
Cipher cipher = Cipher.getInstance(arg0) ;//工厂创建出一个对象
//Key arg1;
//SecretKey key = SecretKeyFactory.getInstance(arg0).generateSecret(arg0) ;
SecretKey key = KeyGenerator.getInstance(arg0).generateKey() ;
//保持Key
FileOutputStream fos = new FileOutputStream("wc_secret.key") ;
ObjectOutputStream oosSecretKey = new ObjectOutputStream(fos) ;
oosSecretKey.writeObject(key) ;
oosSecretKey.close() ;
fos.close() ;
//加密的初始化
cipher.init(Cipher.ENCRYPT_MODE, key) ;
cipher.update("aaab".getBytes()) ;
byte[] bytes = cipher.doFinal(); //加密下
System.out.println(bytes);
//解密
cipher.init(Cipher.DECRYPT_MODE, key) ;
byte[] bytes2 = cipher.doFinal(bytes) ;
System.out.println(new String(bytes2));
}
private static void secretSDepect() throws Exception, NoSuchPaddingException {
String arg0 = "AES"; //加密算法
FileInputStream fis = new FileInputStream("wc_secret.key") ;
ObjectInputStream objIs = new ObjectInputStream(fis) ;
Key key = (Key)objIs.readObject() ;
objIs.close() ;