2015-12-03 60 views
1

我目前有一個使用AES/CBC而沒有隨機數的附件。相反,消息本身包含一個隨機數,密鑰是硬編碼的。我正嘗試在Android上執行相同的操作,以通過BLE與附件進行交換。不知何故,我無法弄清楚如何不使用隨機數來生成Key-class對象。如何在Android中沒有隨機數的情況下進行加密

這裏是希望我能夠做一個例子:

public byte[] encrypt(byte[] key, byte[] input) throws Exception { 
     Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding "); 
     cipher.init(Cipher.ENCRYPT_MODE, key); 
     return cipher.doFinal(input); 
    } 

這是我已經試過:

public byte[] encrypt(byte[] key, byte[] input) throws Exception { 
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); 
    SecureRandom secureRandom = new SecureRandom(key); 
    secureRandom.setSeed(key); 
    keyGenerator.init(128, secureRandom); 
    SecretKey secretkey = keyGenerator.generateKey(); 
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding "); 
    cipher.init(Cipher.ENCRYPT_MODE, secretkey); 
    return cipher.doFinal(input); 
} 
public byte[] encrypt(byte[] key, byte[] input) throws Exception { 
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES/CBC/NoPadding "); 
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding "); 
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); 
    return cipher.doFinal(input); 
} 

不幸的是這兩個加密之前改變的關鍵。

如何使用我的密鑰「原樣」?

回答

0

如果您想用自己的密鑰進行加密而不使用鹽或使用任何隨機密鑰,可以按照以下步驟進行操作。

byte[] keyBuf= new byte[32]; 

    byte[] b= key.getBytes("UTF-8"); 
    int len= b.length; 
    if (len > keyBuf.length) len = keyBuf.length; 

    System.arraycopy(b, 0, keyBuf, 0, len); 
    SecretKey keySpec = new SecretKeySpec(keyBuf, "AES"); 


    byte[] ivBuf= new byte[16]; 
    IvParameterSpec ivSpec = new IvParameterSpec(ivBuf); 

    cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); 

其中key是我的自定義鍵作爲字符串和b我的鍵作爲字節[]。以這種方式初始化密碼可避免醃製,並允許您始終使用自己的密鑰來加密任何內容。

相關問題