聊聊PBE算法

本文主要研究一下PBE算法

PBE

PBE即Password Based Encryption,基于口令的加密,它是一种组合算法,即一般是哈希+对称算法,比如PBEWithMD5AndDES,就是用MD5做哈希,用DES做加解密,而其密钥则是口令+salt基于哈希函数计算而来

java示例

    public void testPBEWithIvParameter() throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException {
        String algorithm = "PBEWithMD5AndDES";
        char[] passwd = "123456".toCharArray();
        PBEKeySpec pbeKeySpec = new PBEKeySpec(passwd);
        SecretKeyFactory kf = SecretKeyFactory.getInstance(algorithm);
        SecretKey key = kf.generateSecret(pbeKeySpec);

        byte[] salt = new byte[8];
        Random random = new Random();
        random.nextBytes(salt);

        Cipher cp = Cipher.getInstance(algorithm);

        IvParameterSpec iv = new IvParameterSpec(RandomUtil.randomBytes(16));
        PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 1000, iv);

        cp.init(Cipher.ENCRYPT_MODE, key, pbeParameterSpec);

        byte[] data = "helloworld".getBytes(StandardCharsets.UTF_8);
        byte[] encrypted = cp.doFinal(data);

        System.out.println(Base64.encode(encrypted));

        Cipher cpDecrypt = Cipher.getInstance(algorithm);
        cpDecrypt.init(Cipher.DECRYPT_MODE, key, pbeParameterSpec);
        byte[] decryptBytes = cpDecrypt.doFinal(encrypted);
        System.out.println(new String(decryptBytes));
    }

几个参数,一个是口令,即passwd,一个是salt,随机盐值,一个是ivParameter

golang示例

func Encrypt(message string, password string, salt []byte) (string, error) {
	keyObtentionIterations := 1000
	md5key, iv := getMd5DerivedKey(password, salt, keyObtentionIterations)
	encrypted, err := desEncrypt([]byte(message), md5key, iv)
	if err != nil {
		return "", err
	}

	result := encrypted
	if includePlainIvInEncryptionResults() {
		result = append(iv, result...)
	}
	if includePlainSaltInEncryptionResults() {
		result = append(salt, result...)
	}
	
	return base64.StdEncoding.EncodeToString(result), nil
}

小结

  • PBE即Password Based Encryption,基于口令的加密,它是一种组合算法,即一般是哈希+对称算法,比如PBEWithMD5AndDES,就是用MD5做哈希,用DES做加解密,而其密钥则是口令+salt基于哈希函数计算而来
  • 当使用固定salt和不使用ivParameter的DES的时候,同一个值,每次加密生成的密文是一样的,而使用随机salt和随机iv的时候,每次生成的密文是不一样的,这个时候密文会包含随机的salt和iv信息,在解密的时候能够正确解出明文

你可能感兴趣的:(安全)