2014-11-15 51 views
0

我必须在Android设备上加密和解密文本。我找到了一些解决方案,但是当我再次加密文本时,结果是不同的。谁能告诉我为什么?Android上的AES加密

这里是我的代码:

public class AESDemo { 


    private static final String password = "test"; 
    private static String salt; 
    private static int pswdIterations = 65536; 
    private static int keySize = 256; 
    private byte[] ivBytes; 

    public String encrypt(String plainText) throws Exception { 

     //get salt 
     salt = generateSalt(); 
     byte[] saltBytes = salt.getBytes("UTF-8"); 

     // Derive the key 
     SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 
     PBEKeySpec spec = new PBEKeySpec(
       password.toCharArray(), 
       saltBytes, 
       //null, 
       pswdIterations, 
       keySize 
     ); 

     SecretKey secretKey = factory.generateSecret(spec); 
     SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); 

     //encrypt the message 
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     cipher.init(Cipher.ENCRYPT_MODE, secret); 
     AlgorithmParameters params = cipher.getParameters(); 
     ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV(); 
     byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8")); 
     //return new Base64().encodeAsString(encryptedTextBytes); 
     return Base64.encodeToString(encryptedTextBytes, Base64.DEFAULT); 
    } 

    @SuppressWarnings("static-access") 
    public String decrypt(String encryptedText) throws Exception { 

     byte[] saltBytes = salt.getBytes("UTF-8"); 
     //byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText); 
     byte[] encryptedTextBytes= Base64.decode(encryptedText, Base64.DEFAULT); 

     // Derive the key 
     SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 
     PBEKeySpec spec = new PBEKeySpec(
       password.toCharArray(), 
       saltBytes, 
       pswdIterations, 
       keySize 
     ); 

     SecretKey secretKey = factory.generateSecret(spec); 
     SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); 

     // Decrypt the message 
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes)); 


     byte[] decryptedTextBytes = null; 
     try { 
      decryptedTextBytes = cipher.doFinal(encryptedTextBytes); 
     } catch (IllegalBlockSizeException e) { 
      e.printStackTrace(); 
     } catch (BadPaddingException e) { 
      e.printStackTrace(); 
     } 

     return new String(decryptedTextBytes); 
    } 

    public String generateSalt() { 
     SecureRandom random = new SecureRandom(); 
     byte bytes[] = new byte[20]; 
     String ss = ""; 
     random.nextBytes(bytes); 
     String s = new String(bytes); 
     return "sare"; 
    } 
} 

我硬编码的盐是一样的,但每次的结果是不同的。谁能告诉我为什么?

回答

0

你的静脉输液处理使我困惑。你可以调用getIV(),但是你在哪里设置了加密的IV?在我看来,你正在使用随机四,这可能解释为什么你每次都得到不同的加密数据。

我建议尝试创建一个动态IvParameterSpec类,并用预设的IV填充它。