您的位置:首页 > 编程语言 > Java开发

Java加密技术相关

2017-05-08 21:38 369 查看
1、ECB加密模式是最简单的模式,每一个数据块之间没有任何关系。因此它不需要也不能使用IV(初始化向量:Initialization vector)。默认的加密模式就是ECB(直接使用"AES"获取算法时)
 
2、其它加密模式需要使用IV,IV的使用方式:
IvParameterSpec iv = new IvParameterSpec(keyBytes);

encypher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, alogorithmBase), iv);
注意进行加密时不指定初始化向量不会报错,但是每次加密的结果都可能不同,不可预知。解密时必须制定初始化向量,否则会抛出异常。
 
3、没有指定IV时,加密器会生成一个IV,生成算法可能是随机算法。可以使用cliper.getIV()来获取其生成的IV。再使用该IV进行解密就没有问题了。通过更换IV也是算法的一种安全保障。
import android.util.Base64;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptUtil {
/**
* close
*
* @param content
* @param key
* @return
*/
public static String encrypt4AES(String content, String key) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(initIv());
SecretKeySpec key1 = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key1, iv);
byte[] encryptedData = cipher.doFinal(content.getBytes());
String encryptResultStr = Base64.encodeToString(encryptedData, Base64.NO_WRAP);//不换行
return encryptResultStr;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 偏移量.保证每次生成密文的唯一性
*
* @return
*/
private static byte[] initIv() {
String iv = "0000000000000000";
return iv.getBytes();
}

/**
* @param content
* @param pass
* @return open
*/
public static String deCiphering(String content, String pass) {

byte[] bytea = Base64.decode(content, Base64.NO_WRAP);
IvParameterSpec iv = new IvParameterSpec(initIv());
Key key = new SecretKeySpec(pass.getBytes(), "AES");

Cipher cipher = null;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);               //与加密时不同MODE:Cipher.DECRYPT_MODE
byte[] ret = cipher.doFinal(bytea);
return new String(ret, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java加密