Java加密技术——PBE算法

   除了DES,我们还知道有DESede(TripleDES,就是3DES)、AES、Blowfish、RC2、RC4(ARCFOUR)等多种对称加密方式,其实现方式大同小异,这里介绍对称加密的另一个算法——PBE

PBE
    PBE——Password-based encryption(基于密码加密)。其特点在于口令由用户自己掌管,不借助任何物理媒体;采用随机数(这里我们叫做盐)杂凑多重加密等方法保证数据的安全性。是一种简便的加密方式。



通过java代码实现如下: Coder类见 Java加密技术(一)
Java代码 复制代码  收藏代码
  1. import java.security.Key;   
  2. import java.util.Random;   
  3.   
  4. import javax.crypto.Cipher;   
  5. import javax.crypto.SecretKey;   
  6. import javax.crypto.SecretKeyFactory;   
  7. import javax.crypto.spec.PBEKeySpec;   
  8. import javax.crypto.spec.PBEParameterSpec;   
  9.   
  10. /**  
  11.  * PBE安全编码组件  
  12.  *   
  13.  * @author 梁栋  
  14.  * @version 1.0  
  15.  * @since 1.0  
  16.  */  
  17. public abstract class PBECoder extends Coder {   
  18.     /**  
  19.      * 支持以下任意一种算法  
  20.      *   
  21.      * <pre>  
  22.      * PBEWithMD5AndDES   
  23.      * PBEWithMD5AndTripleDES   
  24.      * PBEWithSHA1AndDESede  
  25.      * PBEWithSHA1AndRC2_40  
  26.      * </pre>  
  27.      */  
  28.     public static final String ALGORITHM = "PBEWITHMD5andDES";   
  29.   
  30.     /**  
  31.      * 盐初始化  
  32.      *   
  33.      * @return  
  34.      * @throws Exception  
  35.      */  
  36.     public static byte[] initSalt() throws Exception {   
  37.         byte[] salt = new byte[8];   
  38.         Random random = new Random();   
  39.         random.nextBytes(salt);   
  40.         return salt;   
  41.     }   
  42.   
  43.     /**  
  44.      * 转换密钥<br>  
  45.      *   
  46.      * @param password  
  47.      * @return  
  48.      * @throws Exception  
  49.      */  
  50.     private static Key toKey(String password) throws Exception {   
  51.         PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());   
  52.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);   
  53.         SecretKey secretKey = keyFactory.generateSecret(keySpec);   
  54.   
  55.         return secretKey;   
  56.     }   
  57.   
  58.     /**  
  59.      * 加密  
  60.      *   
  61.      * @param data  
  62.      *            数据  
  63.      * @param password  
  64.      *            密码  
  65.      * @param salt  
  66.      *            盐  
  67.      * @return  
  68.      * @throws Exception  
  69.      */  
  70.     public static byte[] encrypt(byte[] data, String password, byte[] salt)   
  71.             throws Exception {   
  72.   
  73.         Key key = toKey(password);   
  74.   
  75.         PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);   
  76.         Cipher cipher = Cipher.getInstance(ALGORITHM);   
  77.         cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);   
  78.   
  79.         return cipher.doFinal(data);   
  80.   
  81.     }   
  82.   
  83.     /**  
  84.      * 解密  
  85.      *   
  86.      * @param data  
  87.      *            数据  
  88.      * @param password  
  89.      *            密码  
  90.      * @param salt  
  91.      *            盐  
  92.      * @return  
  93.      * @throws Exception  
  94.      */  
  95.     public static byte[] decrypt(byte[] data, String password, byte[] salt)   
  96.             throws Exception {   
  97.   
  98.         Key key = toKey(password);   
  99.   
  100.         PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);   
  101.         Cipher cipher = Cipher.getInstance(ALGORITHM);   
  102.         cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);   
  103.   
  104.         return cipher.doFinal(data);   
  105.   
  106.     }   
  107. }  
import java.security.Key;
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;

/**
 * PBE安全编码组件
 * 
 * @author 梁栋
 * @version 1.0
 * @since 1.0
 */
public abstract class PBECoder extends Coder {
	/**
	 * 支持以下任意一种算法
	 * 
	 * <pre>
	 * PBEWithMD5AndDES 
	 * PBEWithMD5AndTripleDES 
	 * PBEWithSHA1AndDESede
	 * PBEWithSHA1AndRC2_40
	 * </pre>
	 */
	public static final String ALGORITHM = "PBEWITHMD5andDES";

	/**
	 * 盐初始化
	 * 
	 * @return
	 * @throws Exception
	 */
	public static byte[] initSalt() throws Exception {
		byte[] salt = new byte[8];
		Random random = new Random();
		random.nextBytes(salt);
		return salt;
	}

	/**
	 * 转换密钥<br>
	 * 
	 * @param password
	 * @return
	 * @throws Exception
	 */
	private static Key toKey(String password) throws Exception {
		PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
		SecretKey secretKey = keyFactory.generateSecret(keySpec);

		return secretKey;
	}

	/**
	 * 加密
	 * 
	 * @param data
	 *            数据
	 * @param password
	 *            密码
	 * @param salt
	 *            盐
	 * @return
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] data, String password, byte[] salt)
			throws Exception {

		Key key = toKey(password);

		PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);

		return cipher.doFinal(data);

	}

	/**
	 * 解密
	 * 
	 * @param data
	 *            数据
	 * @param password
	 *            密码
	 * @param salt
	 *            盐
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] data, String password, byte[] salt)
			throws Exception {

		Key key = toKey(password);

		PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

		return cipher.doFinal(data);

	}
}


再给出一个测试类:
Java代码 复制代码  收藏代码
  1. import static org.junit.Assert.*;   
  2.   
  3. import org.junit.Test;   
  4.   
  5. /**  
  6.  *   
  7.  * @author 梁栋  
  8.  * @version 1.0  
  9.  * @since 1.0  
  10.  */  
  11. public class PBECoderTest {   
  12.   
  13.     @Test  
  14.     public void test() throws Exception {   
  15.         String inputStr = "abc";   
  16.         System.err.println("原文: " + inputStr);   
  17.         byte[] input = inputStr.getBytes();   
  18.   
  19.         String pwd = "efg";   
  20.         System.err.println("密码: " + pwd);   
  21.   
  22.         byte[] salt = PBECoder.initSalt();   
  23.   
  24.         byte[] data = PBECoder.encrypt(input, pwd, salt);   
  25.   
  26.         System.err.println("加密后: " + PBECoder.encryptBASE64(data));   
  27.   
  28.         byte[] output = PBECoder.decrypt(data, pwd, salt);   
  29.         String outputStr = new String(output);   
  30.   
  31.         System.err.println("解密后: " + outputStr);   
  32.         assertEquals(inputStr, outputStr);   
  33.     }   
  34.   
  35. }  
import static org.junit.Assert.*;

import org.junit.Test;

/**
 * 
 * @author 梁栋
 * @version 1.0
 * @since 1.0
 */
public class PBECoderTest {

	@Test
	public void test() throws Exception {
		String inputStr = "abc";
		System.err.println("原文: " + inputStr);
		byte[] input = inputStr.getBytes();

		String pwd = "efg";
		System.err.println("密码: " + pwd);

		byte[] salt = PBECoder.initSalt();

		byte[] data = PBECoder.encrypt(input, pwd, salt);

		System.err.println("加密后: " + PBECoder.encryptBASE64(data));

		byte[] output = PBECoder.decrypt(data, pwd, salt);
		String outputStr = new String(output);

		System.err.println("解密后: " + outputStr);
		assertEquals(inputStr, outputStr);
	}

}


控制台输出:
Console代码 复制代码  收藏代码
  1. 原文: abc   
  2. 密码: efg   
  3. 加密后: iCZ0uRtaAhE=   
  4.   
  5. 解密后: abc  

    后续我们会介绍非对称加密算法,如RSA、DSA、DH、ECC等。



相关链接:
Java加密技术(一)——BASE64与单向加密算法MD5&SHA&MAC
Java加密技术(二)——对称加密DES&AES
Java加密技术(三)——PBE算法
Java加密技术(四)——非对称加密算法RSA
Java加密技术(五)——非对称加密算法的由来DH
Java加密技术(六)——数字签名算法DSA
Java加密技术(七)——非对称加密算法最高ECC
Java加密技术(八)——数字证书
Java加密技术(九)——初探SSL
Java加密技术(十)——单向认证
Java加密技术(十一)——双向认证
Java加密技术(十二)——*.PFX(*.p12)&个人信息交换文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Go语言实现PBE加密算法的示例代码: ```go package main import ( "crypto/cipher" "crypto/des" "crypto/md5" "encoding/base64" "fmt" ) func main() { // 设置加密参数 password := "123456" // 密码 salt := "salt" // 盐值 iterations := 1000 // 迭代次数 // 生成密钥 key := pbkdf1([]byte(password), []byte(salt), iterations, 8) // 加密明文 plaintext := "hello world" ciphertext, err := pbeEncrypt([]byte(plaintext), key) if err != nil { panic(err) } // 输出加密结果 fmt.Println(base64.StdEncoding.EncodeToString(ciphertext)) // 解密密文 decrypted, err := pbeDecrypt(ciphertext, key) if err != nil { panic(err) } // 输出解密结果 fmt.Println(string(decrypted)) } // PBE加密 func pbeEncrypt(plaintext []byte, key []byte) ([]byte, error) { // 创建加密器 block, err := des.NewCipher(key) if err != nil { return nil, err } iv := make([]byte, block.BlockSize()) stream := cipher.NewCTR(block, iv) // 加密明文 ciphertext := make([]byte, len(plaintext)) stream.XORKeyStream(ciphertext, plaintext) return ciphertext, nil } // PBE解密 func pbeDecrypt(ciphertext []byte, key []byte) ([]byte, error) { // 创建解密器 block, err := des.NewCipher(key) if err != nil { return nil, err } iv := make([]byte, block.BlockSize()) stream := cipher.NewCTR(block, iv) // 解密密文 plaintext := make([]byte, len(ciphertext)) stream.XORKeyStream(plaintext, ciphertext) return plaintext, nil } // PBKDF1算法 func pbkdf1(password []byte, salt []byte, iterations int, keyLen int) []byte { key := password for i := 0; i < iterations; i++ { data := append(key, salt...) hash := md5.Sum(data) key = hash[:] } return key[:keyLen] } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值