java无法更改Base64解码器中的密码密钥
我有一个预先编写的代码,用于对给定的纯文本进行加密,反之亦然
该类有3个方法,其中2个方法可分别用于加密和解密
public class SqlCipherUtil {
private Cipher ecipher;
private Cipher dcipher;
public String encryptString(String pStrPlainText) {
try {
generateKey();
byte[] utf8 = pStrPlainText.getBytes("UTF8");
byte[] enc = this.ecipher.doFinal(utf8);
return new BASE64Encoder().encode(enc);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String decryptString(String pStrCipherText){
try {
generateKey();
byte[] dec = new BASE64Decoder().decodeBuffer(pStrCipherText);
byte[] utf8 = this.dcipher.doFinal(dec);
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* This method is used to generate the encrypted key.
*/
private void generateKey() {
try {
byte[] decodedStr = new BASE64Decoder().decodeBuffer("rA/LUdBA/hA=");
SecretKey key = new SecretKeySpec(decodedStr, "DES");
this.ecipher = Cipher.getInstance("DES");
this.dcipher = Cipher.getInstance("DES");
this.ecipher.init(1, key);
this.dcipher.init(2, key);
} catch (Exception e) {
e.printStackTrace();
}
}
}
类中存在的键不能更改为任何其他键
在第byte[] decodedStr = new BASE64Decoder().decodeBuffer("rA/LUdBA/hA=");
行中,
这是一个例外
java.security.InvalidKeyException: Invalid key length: 9 bytes
at com.sun.crypto.provider.DESCipher.engineGetKeySize(DashoA13*..)
at javax.crypto.Cipher.b(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
我尝试了下面的代码,得到的数组正好是8个字节
public static void main(String[] args) throws IOException {
byte[] decodedStr = new BASE64Decoder().decodeBuffer("rA/LUdBA/hA=");
for(byte b : decodedStr){
System.out.print(b);
System.out.print(" ");
}
}
}
该键的任何其他组合将使字节数组大小大于8或小于7
获取字节数组大小8背后的概念是什么
要使用自定义组合键或自定义生成的键,应该做些什么
请回答这两个问题
# 1 楼答案
如果目标是对字符串进行编码和解码,请使用
Base64
对于其他数据类型:根据内存分配大小,它可以是
java.lang.OutOfMemoryError
# 2 楼答案
新的based-64编码密钥的长度必须为12个字符,以一个字符结尾,并且只有一个
=
字符在base-64中,字符
=
是一个填充字符,它只能出现在编码字符串的末尾。Base-64编码从每个3字节的输入块中输出4个字符的块。如果输入长度不是3的倍数,则填充最后一个块在编码密钥“rA/LUdBA/hA=”中,有12个字符,可以编码9个字节。但是最后一个字符是padding,这意味着最后一个字节应该被忽略,剩下8个字节
首先,你不应该使用DES。它太脆弱和不安全了。但一般来说,在Java中生成安全密钥的正确过程是使用^{} 类。对于(不安全的)DES,您可以生成密钥并使用base-64对其进行编码,如下所示:
要使用密钥,请按如下方式解码:
# 3 楼答案
我对此表示怀疑。你可能添加或删除了错误的字符;或者在错误的位置。见:http://en.wikipedia.org/wiki/Base64
是的,9字节不是DES的有效密钥长度。你可以把它缩短到合适的长度。因为base64字符串的长度为3x4个字符,所以会得到9个字节,这将被解码为3x3=9个字符。削减产量
DES使用56位键。8字节=64位,因此密钥有足够的位
让用户输入至少包含7个字符(56位)的密钥。 我真的不明白为什么在这个示例中使用base64——可能只是因为你从某个地方复制了它?你只需要几个随机字节。获取这些数据的常用方法是根据用户提供的任何输入构建一个哈希,并使用该哈希中的字节