gpt4 book ai didi

java - 使用blowfish Java加密后无法解密

转载 作者:行者123 更新时间:2023-12-02 06:33:28 25 4
gpt4 key购买 nike

您好,我是 Java 新手,遇到以下问题:我正在尝试使用河豚算法加密用户的密码,但是当我尝试解密它以检查身份验证时,它无法解密它由于某种原因。

public static String encryptBlowFish(String to_encrypt, String salt){
String dbpassword = null;
try{
SecretKeySpec skeySpec = new SecretKeySpec( salt.getBytes(), "Blowfish" );

// Instantiate the cipher.
Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

//byte[] encrypted = cipher.doFinal( URLEncoder.encode(data).getBytes() );
byte[] encrypted = cipher.doFinal( to_encrypt.getBytes() );
dbpassword = new String(encrypted);
} catch (Exception e) {
System.out.println("Exception while encrypting");
e.printStackTrace();
dbpassword = null;
} finally {
return dbpassword;
}
}

public static String decryptBlowFish(String to_decrypt, String salt){
String dbpassword = null;
try{
SecretKeySpec skeySpec = new SecretKeySpec( salt.getBytes(), "Blowfish" );

// Instantiate the cipher.
Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);

//byte[] encrypted = cipher.doFinal( URLEncoder.encode(data).getBytes() );
byte[] encrypted = cipher.doFinal( to_decrypt.getBytes() );
dbpassword = new String(encrypted);
} catch (Exception e) {
System.out.println("Exception while decrypting");
e.printStackTrace();
dbpassword = null;
} finally {
return dbpassword;
}
}

当我调用解密函数时,出现以下错误:java.security.InvalidKeyException:缺少参数

有什么想法吗?谢谢

最佳答案

你在这里做错了很多事情:

  • 您正在将加密值转换为字符串。并非所有字节都是有效的字符串。将字节作为二进制 blob 直接存储在数据库中,而不是作为字符串(或先将其转换为十六进制或 base64)。

  • 您混淆了盐和 key 。您在代码中调用 salt 的东西实际上是一个私钥。你看起来根本就没有真正的盐。

  • 您正在加密密码。这意味着您需要将 key 存储在某处(您不能将其存储在数据库中,否则窃取数据库的任何人都将能够解密密码)。相反,您应该使用哈希值。

  • 即使如此,您也不应该以这种方式存储密码。即使你正确使用盐也不会。如今,破解简单的散列密码太容易了,即使是加盐的密码。相反,请使用 bcrypt 库或 PBKDF2。

here are instructions for doing this correctly 。请注意,如果您遵循这些说明,就可以将密码存储为字符串(它已为您正确转换)。

关于java - 使用blowfish Java加密后无法解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19878196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com