解密可以用一个字符串.getBytes(),但失败了安全随机生成()

2024-06-01 06:12:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究如何使用AES进行跨平台(Android&Python)加密和解密,而且如果我使用基于String的IV,我似乎可以成功地传输数据。但是,如果我切换到使用使用SecureRandom.generateSeed()生成的字节,就会出现问题。 密钥是预共享的。在

正在工作的Android代码(删除try/catch块以保持其简短):

String SecretKey = "0123456789abcdef";
String iv = "fedcba9876543210";

IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
SecretKeySpec keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

//Initialize the cipher
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); 

String message = "What's up?";
byte[] encrypted = cipher.doFinal(message.getBytes());

//Send the data
outputStream.write(encrypted);

有一个小的传输头,让客户机知道传入消息的大小,但我认为它与此无关,所以我将其忽略了。 接收此消息的Python代码如下所示:

^{pr2}$

结果如下:

read [What's up]

如果我在Java代码中更改两行:

SecureRandom rnd = new SecureRandom();
IvParameterSpec ivspec = new IvParameterSpec(rnd.generateSeed(16));

Python输出变成:

read [?=H��m��lڈ�1ls]

我想知道SecureRandom有什么变化?我在默认情况下读到字符串.getBytes()返回平台默认编码(对于Android 4.0),所以我想知道是否必须在Python端对使用SecureRandom生成的IV进行一些操作。。?在


Tags: 代码newstringandroidaesciphersecretkeyiv
1条回答
网友
1楼 · 发布于 2024-06-01 06:12:48

需要告诉接受者静脉注射是什么。看看this Wikipedia entry中关于CBC的部分:你可以看到加密的n块消息由n+1个块组成,附加块是IV。没有标准的协议来传输它,但是我看到的每一个代码都是通过在消息前面加上IV来实现的,这确实是一件很自然的事情,多亏了CBC的纠错特性,即使在代码稍微出错的时候也能正常工作。例如,您可以找到使用常量IV但在纯文本前面加上一个随机块的代码,它基本上以不同的方式执行相同的操作。有时你甚至在书中也会发现这种代码,比如InlineIvCBCExample.java在大卫·胡克的第二章中,其他方面非常好book。在

我推荐了以下AES/CBC/PKCS7填充方式:

byte[] plaintext = ...;
byte[] key = ...;

// get iv
SecureRandom rnd = new SecureRandom();
byte[] iv = rnd.getBytes(16);
IvParameterSpec ivSpec = new IvParameterSpec(iv);   

// encrypt
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] ciphertext = cipher.doFinal(plaintext);

// copy to result
byte[] result = new byte[iv.length + ciphertext.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(ciphertext, 0 , result, iv.length, ciphertext.length);

相关问题 更多 >