java安全2--根据输入密码方式对数据加密解密

 
public class SecretKeyTest {

	public static void main(String[] args) throws Exception{

		SecrectEncrypt();

		SecretDecrpy();

	}

	private static void SecrectEncrypt() throws Exception {
		
		//根据输入的值得到密钥
		Cipher cipher=Cipher.getInstance("PBEWithMD5AndDES");
//		SecretKey key=KeyGenerator.getInstance("AES").generateKey();
		//Key子类 SecretKey,publicKey/PrivateKey
		SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec("abcdefg".toCharArray()));
		//保存密钥并在控制台输出密钥
		FileOutputStream foskey = new FileOutputStream("c://k.txt");
		ObjectOutputStream ooskey = new ObjectOutputStream(foskey);
		ObjectOutputStream sysout=new ObjectOutputStream(System.out);
		System.out.println("解密前密钥为:");
		sysout.writeObject(key);
		ooskey.writeObject(key);
		ooskey.close();
		
		foskey.close();
		//加密
		cipher.init(Cipher.ENCRYPT_MODE, key,new PBEParameterSpec(new byte[]{1,2,3,4,5,6,7,8}, 8));
		byte[] results = cipher.doFinal("保存的就是我这个字条串".getBytes());
		//保存加密后的数据
		System.out.println("保存前的数据为:保存的就是我这个字条串");
		FileOutputStream fosDate = new FileOutputStream("c://data.txt");
		fosDate.write(results);
		fosDate.close();
	}
	private static void SecretDecrpy() throws Exception {
		Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
		SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec("abcdefg".toCharArray()));
		
		ObjectOutputStream sysout=new ObjectOutputStream(System.out);
		System.out.println("解密时的密钥为:");
		sysout.writeObject(key);
		
		
		cipher.init(Cipher.DECRYPT_MODE, key,new PBEParameterSpec(new byte[]{1,2,3,4,5,6,7,8}, 8));
		
		FileInputStream fisdate = new FileInputStream("c://data.txt");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		copyStream(fisdate, baos);

		byte[] result = cipher.doFinal(baos.toByteArray());
		fisdate.close();
		baos.close();

		System.out.println("解密后的数据为:"+new String(result));
		
		
	}
	private static void copyStream(InputStream ips,OutputStream ops) throws Exception {
		
		byte[] buf = new byte[1024];
		int len=ips.read(buf);
		while (len !=- 1) {
			ops.write(buf, 0,len);
			len = ips.read(buf);
			
		}
	}
}

你可能感兴趣的:(java,加密,exception,String,解密,byte)