Java AES初始化向量随机化
我正在尝试使用初始化向量重用AES实现。到目前为止,我只实现了数据在android应用程序上加密,在php服务器上解密的部分。然而,该算法有一个主要漏洞,即初始化向量是常量,我最近发现这是一个主要的安全漏洞。不幸的是,我已经在应用程序的每个活动和服务器端的所有脚本上实现了它。 我想知道是否有办法修改这段代码,使初始化向量随机化,以及是否有办法将该向量发送到服务器(反之亦然),以便每次对消息进行加密时,模式都会不断变化。以下是我的Android和PHP代码: 安卓:Java AES初始化向量随机化,java,php,android,encryption,aes,Java,Php,Android,Encryption,Aes,我正在尝试使用初始化向量重用AES实现。到目前为止,我只实现了数据在android应用程序上加密,在php服务器上解密的部分。然而,该算法有一个主要漏洞,即初始化向量是常量,我最近发现这是一个主要的安全漏洞。不幸的是,我已经在应用程序的每个活动和服务器端的所有脚本上实现了它。 我想知道是否有办法修改这段代码,使初始化向量随机化,以及是否有办法将该向量发送到服务器(反之亦然),以便每次对消息进行加密时,模式都会不断变化。以下是我的Android和PHP代码: 安卓: package com.fyp
package com.fyp.merchantapp;
// This file and its contents have been taken from http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php.html
//Ownership has been acknowledged
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MCrypt {
static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
private String iv = "MyNameIsHamza100";//(IV)
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;
private String SecretKey = "MyNameIsBilal100";//(SECRETKEY)
public MCrypt()
{
ivspec = new IvParameterSpec(iv.getBytes());
keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
try {
cipher = Cipher.getInstance("AES/CBC/NoPadding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public byte[] encrypt(String text) throws Exception
{
if(text == null || text.length() == 0)
throw new Exception("Empty string");
byte[] encrypted = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = cipher.doFinal(padString(text).getBytes());
} catch (Exception e)
{
throw new Exception("[encrypt] " + e.getMessage());
}
return encrypted;
}
public byte[] decrypt(String code) throws Exception
{
if(code == null || code.length() == 0)
throw new Exception("Empty string");
byte[] decrypted = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
decrypted = cipher.doFinal(hexToBytes(code));
//Remove trailing zeroes
if( decrypted.length > 0)
{
int trim = 0;
for( int i = decrypted.length - 1; i >= 0; i-- ) if( decrypted[i] == 0 ) trim++;
if( trim > 0 )
{
byte[] newArray = new byte[decrypted.length - trim];
System.arraycopy(decrypted, 0, newArray, 0, decrypted.length - trim);
decrypted = newArray;
}
}
} catch (Exception e)
{
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
public static String bytesToHex(byte[] buf)
{
char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i)
{
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}
private static String padString(String source)
{
char paddingChar = 0;
int size = 16;
int x = source.length() % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++)
{
source += paddingChar;
}
return source;
}
}
package com.fyp.merchantapp;
//此文件及其内容取自http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php.html
//所有权已得到承认
导入java.security.NoSuchAlgorithmException;
导入javax.crypto.Cipher;
导入javax.crypto.NoSuchPaddingException;
导入javax.crypto.spec.IvParameterSpec;
导入javax.crypto.spec.SecretKeySpec;
公共类MCrypt{
静态字符[]十六进制字符={0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
私有字符串iv=“MyNameIsHamza100”/(iv)
私有IvParameterSpec ivspec;
私有SecretKeySpec-keyspec;
专用密码;
私有字符串SecretKey=“mynameisbill100”;/(SecretKey)
公共MCrypt()
{
ivspec=新的IvParameterSpec(iv.getBytes());
keyspec=newsecretkeyspec(SecretKey.getBytes(),“AES”);
试一试{
cipher=cipher.getInstance(“AES/CBC/NoPadding”);
}捕获(无算法异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(无此填充例外){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
公共字节[]加密(字符串文本)引发异常
{
if(text==null | | text.length()==0)
抛出新异常(“空字符串”);
字节[]加密=空;
试一试{
cipher.init(cipher.ENCRYPT_模式,keyspec,ivspec);
加密=cipher.doFinal(padString(text).getBytes());
}捕获(例外e)
{
抛出新异常(“[encrypt]”+e.getMessage());
}
返回加密;
}
公共字节[]解密(字符串代码)引发异常
{
if(code==null | | code.length()==0)
抛出新异常(“空字符串”);
字节[]已解密=空;
试一试{
cipher.init(cipher.DECRYPT_模式,keyspec,ivspec);
解密=cipher.doFinal(十六字节(代码));
//删除尾随零
如果(已解密。长度>0)
{
int trim=0;
对于(int i=decrypted.length-1;i>=0;i--)如果(decrypted[i]=0)trim++;
如果(修剪>0)
{
byte[]newArray=新字节[decrypted.length-trim];
System.arraycopy(已解密,0,newArray,0,解密.length-trim);
解密=新数组;
}
}
}捕获(例外e)
{
抛出新异常(“[decrypt]”+e.getMessage());
}
返回解密;
}
公共静态字符串bytesToHex(字节[]buf)
{
char[]chars=新字符[2*buf.长度];
对于(int i=0;i>>4];
字符[2*i+1]=十六进制字符[buf[i]&0x0F];
}
返回新字符串(字符);
}
公共静态字节[]十六进制字节(字符串str){
如果(str==null){
返回null;
}else if(str.length()<2){
返回null;
}否则{
int len=str.length()/2;
字节[]缓冲区=新字节[len];
对于(int i=0;i
直接回答您的问题:您只需生成一个随机IV并将其作为密文的前缀。在将密文编码为十六进制之前,您需要这样做。然后在解密过程中,首先解码,然后“删除”IV字节,初始化IV,最后解密密文以获得明文
请注意,在CBC模式下,AES的IV将始终为16字节,因此不需要直接在任何位置包含IV长度。我在“remove”周围使用引号作为IvParameterSpec
asCipher。doFinal
接受带偏移量和长度的缓冲区;不需要将字节复制到不同的数组
注:
- 密钥不应该是字符串;查找PBKDF(如PBKDF2)以从密码或密码短语派生密钥
- CBC通常容易受到填充oracle攻击;但是,通过保持PHP的零填充,您可能意外地避免了攻击
- CBC不提供完整性保护,因此请注意,对手可能会在解密失败的情况下更改密文
- 如果使用文本的底层代码生成错误,则您可能容易受到纯文本oracle攻击(填充oracle攻击只是更大的纯文本oracle组的一部分)
- 您的Java代码是不平衡的;加密和解密模式要么执行十六进制编码/解码,要么不执行
- 异常处理当然不好(尽管这可能只是示例)
将在Android上使用UTF-8,但在Windows上的Java SE上可能使用Windows-1252,因此如果不小心,很容易生成错误的键-始终定义要使用的字符集String#getBytes()
若要使用共享密钥进行通信,请在PSK_uu密码套件之一定义的预共享密钥模式下尝试TLS。使用secureRandom()将IV生成为16字节数组然后将带有密文的IV发送到服务器。服务器接收这两个值并用接收到的IV解密数据。但老实说,我不知道为什么需要TLS上的这一额外加密层,因为它似乎没有增加额外的价值。哦,太好了,另一个Android代码片段需要对抗。你呢
<?php
class MCrypt
{
private $iv = 'MyNameIsHamza100'; #Same as in JAVA
private $key = 'MyNameIsBilal100'; #Same as in JAVA
function __construct()
{
}
/**
* @param string $str
* @param bool $isBinary whether to encrypt as binary or not. Default is: false
* @return string Encrypted data
*/
function encrypt($str, $isBinary = false)
{
$iv = $this->iv;
$str = $isBinary ? $str : utf8_decode($str);
$td = mcrypt_module_open('rijndael-128', ' ', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $isBinary ? $encrypted : bin2hex($encrypted);
}
/**
* @param string $code
* @param bool $isBinary whether to decrypt as binary or not. Default is: false
* @return string Decrypted data
*/
function decrypt($code, $isBinary = false)
{
$code = $isBinary ? $code : $this->hex2bin($code);
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', ' ', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$decrypted = mdecrypt_generic($td, $code);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $isBinary ? trim($decrypted) : utf8_encode(trim($decrypted));
}
protected function hex2bin($hexdata)
{
$bindata = '';
for ($i = 0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}
}
?>