欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

对称加密之基于口令的加密解密

程序员文章站 2024-03-14 14:21:04
...

代码如下:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class test1 {

	// 基于口令的加密
	public void PBEEnc(String s, String password) throws Exception {
		char[] passwd = password.toCharArray();
		PBEKeySpec pbks = new PBEKeySpec(passwd);
		SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
		SecretKey k = kf.generateSecret(pbks);
		byte[] salt = new byte[8];
		Random r = new Random();
		r.nextBytes(salt);
		Cipher cp = Cipher.getInstance("PBEWithMD5AndDES");
		PBEParameterSpec ps = new PBEParameterSpec(salt, 1000);
		cp.init(Cipher.ENCRYPT_MODE, k, ps);
		byte ptext[] = s.getBytes("UTF8");
		byte ctext[] = cp.doFinal(ptext);
		// 将盐和加密结果合并在一起保存为密文
		FileOutputStream f = new FileOutputStream("PBEEnc.dat");
		f.write(salt);
		f.write(ctext);
		// 打印加密结果
		System.out.println("加密后密文:"+new String(ctext));

	}

	// 基于口令的解密
	public void PBEDec(String password) throws Exception {
		char[] passwd = password.toCharArray();
		PBEKeySpec pbks = new PBEKeySpec(passwd);
		SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
		SecretKey k = kf.generateSecret(pbks);
		byte[] salt = new byte[8];
		FileInputStream f = new FileInputStream("PBEEnc.dat");
		f.read(salt);
		int num = f.available();
		byte[] ctext = new byte[num];
		f.read(ctext);
		Cipher cp = Cipher.getInstance("PBEWithMD5AndDES");

		PBEParameterSpec ps = new PBEParameterSpec(salt, 1000);
		cp.init(Cipher.DECRYPT_MODE, k, ps);
		byte ptext[] = cp.doFinal(ctext);
		System.out.println("解密后字符串:"+new String(ptext));
	}

	public static void main(String args[]) throws Exception {
		String str = "Hello World!";
		String passwd = "123456";
		test1 t = new test1();
		System.out.println("加密前原文:"+str);
		t.PBEEnc(str,passwd);
		t.PBEDec(passwd);
	}
}
 
相关标签: F#

上一篇: AES页面加解密

下一篇: gRPC 初识