我有以下类用于存储加密的首选项以与我的应用程序一起使用(使用不支持OAuth的第三方网站的界面)...
public class CryptoTranslator {
private static SecretKey SEC_KEY;
/**
* @return the sEC_KEY
*/
public static SecretKey getSEC_KEY() {
return SEC_KEY;
}
public static String getSEC_KEY_String(){
return Base64.encodeToString(SEC_KEY.getEncoded(), Base64.DEFAULT);
}
/**
* @param sEC_KEY the sEC_KEY to set
*/
public static void setSEC_KEY(SecretKey sEC_KEY) {
SEC_KEY = sEC_KEY;
}
public static void setSEC_KEY_STRING(String sEC_KEY){
byte[] key = Base64.decode(sEC_KEY, Base64.DEFAULT);
SEC_KEY = new SecretKeySpec(key, 0, key.length, "AES");
}
public static void generateKey() throws NoSuchAlgorithmException {
// Generate a 256-bit key
final int outputKeyLength = 256;
SecureRandom secureRandom = new SecureRandom();
// Do *not* seed secureRandom! Automatically seeded from system entropy.
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(outputKeyLength, secureRandom);
SecretKey key = keyGenerator.generateKey();
SEC_KEY = key;
}
private static byte[] getRawKey() throws Exception {
if (SEC_KEY == null){
generateKey();
}
byte[] raw = SEC_KEY.getEncoded();
return raw;
}
/**
*
*
* @param clear clear text string
* @param mode this should either be Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE
* @return
* @throws Exception
*/
private static String translate(String clear, int mode) throws Exception {
if(mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE)
throw new IllegalArgumentException("Encryption invalid. Mode should be either Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE");
SecretKeySpec skeySpec = new SecretKeySpec(getRawKey(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(mode, skeySpec);
byte[] encrypted = cipher.doFinal(clear.getBytes());
return new String(encrypted);
}
public static String encrypt(String clear) throws Exception {
return translate(clear,Cipher.ENCRYPT_MODE);
}
public static String decrypt(String encrypted) throws Exception {
return translate(encrypted,Cipher.DECRYPT_MODE);
}
}
所以现在我加密并存储了数据。现在我想把它拉出来......
String secString = settings.getString(SEC_KEY, null);
if (secString == null) {
try {
CryptoTranslator.generateKey();
settings.edit()
.putString(SEC_KEY,
CryptoTranslator.getSEC_KEY_String()).commit();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
CryptoTranslator.setSEC_KEY_STRING(secString);
}
try {
getUserNamePassword();
} catch (Exception ex) {
Log.i("Preferences",
"There was an issue getting username and password");
isStored = CRED_STATUS_DEF;
}
...
private static void getUserNamePassword() throws Exception {
isStored = settings.getBoolean(CRED_STATUS, CRED_STATUS_DEF);
if (isStored) {
if (settings.contains(USERNAME_KEY))
username = settings.getString(USERNAME_KEY, "");
if (settings.contains(PASSWORD_KEY))
password = settings.getString(PASSWORD_KEY, "");
}
isUsernamePasswordValid();
if (isStored) {
String username2 = CryptoTranslator.decrypt(username);
Log.d("Security", "Username encrypted");
String password2 = CryptoTranslator.decrypt(password);
username = username2;
password = password2;
Log.d("Security", "Password encrypted");
}
}
但是这给了我以下错误....
javax.crypto.IllegalBlockSizeException:解密时最后一个块不完整
有人能看出我做错了吗?
更新
根据回复,我继续将代码更改为以下内容......
public static final int IV_LENGTH = 16;
private static final String RANDOM_ALGORITHM = "SHA1PRNG";
...
private static String translate(String clear, int mode) throws Exception {
if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE)
throw new IllegalArgumentException(
"Encryption invalid. Mode should be either Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE");
SecretKeySpec skeySpec = new SecretKeySpec(getRawKey(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(generateIv());
cipher.init(mode, skeySpec, ivSpec);
byte[] encrypted = cipher.doFinal(clear.getBytes());
return new String(encrypted);
}
...
private static byte[] generateIv() throws NoSuchAlgorithmException,
NoSuchProviderException {
SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM);
byte[] iv = new byte[IV_LENGTH];
random.nextBytes(iv);
return iv;
}
现在我明白了......
javax.crypto.BadPaddingException:pad block corrupted
尝试使用十六进制更改为...
private static byte[] translate(byte[] val, int mode) throws Exception {
if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE)
throw new IllegalArgumentException(
"Encryption invalid. Mode should be either Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE");
SecretKeySpec skeySpec = new SecretKeySpec(getRawKey(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(generateIv());
cipher.init(mode, skeySpec, ivSpec);
byte[] encrypted = cipher.doFinal(val);
return encrypted;
}
这似乎几乎工作(我正在恢复.com)但是这些字符仍然非常混乱。 public static String encrypt(String clear)throws Exception { byte [] test = translate(clear.getBytes(),Cipher.ENCRYPT_MODE); return new String(Hex.encodeHex(test)); }
public static String decrypt(String encrypted) throws Exception {
return new String(translate(Hex.decodeHex(encrypted.toCharArray()), Cipher.DECRYPT_MODE));
}
*转换为十六进制和后退已经搞砸了。
答案 0 :(得分:2)
因此您的代码存在一些问题。
首先,AES密码的输出不是字符数据,您通过尝试将其设置为字符串来破坏密文。当您尝试解密受损的密文时,它的长度是错误的。如果要将密文存储在字符串中,然后在解密之前将其解码回byte[]
,则需要对密文进行Base64或Hex编码。
其次,当您为密码规范仅指定AES
时,Java会将其扩展为AES/ECB/PKCS5Padding
。如果您打算加密超过1个数据块(AES为16个字节),ECB
是一种不安全的密码模式。我建议您切换到不同的规范AES/CBC/PKCS5Padding
应该是可以接受的。使用ECB
以外的模式将需要初始化向量(IV)。 IV应该是随机生成的,但不需要保密,因此您可以将密文存储为明文,因为您需要它来解密。初始化向量需要长度为一个块(AES为16个字节)。不要使用相同的AES密钥重复使用相同的IV,为每个正在进行的加密生成新的IV。
最后,如果您要在第三方服务中存储IV +密文,我建议您添加MAC(例如HMACSHA1)。在尝试解密之前,MAC将确保IV +密文的完整性。 MAC也需要一个密钥,你不应该使用你为密码本身生成的相同密钥。您可以将生成的MAC添加到IV +密文,因此现在存储MAC + IV +密文。
答案 1 :(得分:0)
Android AES客户端+ PHP AES服务器端会抛出此错误:)
解决方案是:
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
请在互联网上搜索完整的源代码。我在NDA下并懒散地将我的整个代码写成匿名,但我相信你会找到它。