2014-11-09 62 views
0

我想以byte []形式獲取一段明文,一個對稱密鑰(來自之前的計算),並輸出一個密文。 cipherText = encrypt(plainText,sharedSecret) 如何合併純文本和共享密鑰?使用Java中的對稱密鑰byte []加密消息

public static String encrypt(String plainText, byte[] sharedSecret){ 
     String cipherText = ""; 
     //combining the sharedSecret with the plainText 
     return cipherText; 
    } 
+0

退房Cipher類。這個網站和其他地方有成千上萬的例子。 – 2014-11-09 01:41:18

+0

你還需要一個IV。 – SLaks 2014-11-09 02:24:32

+0

您能找到解決方案嗎? – 2014-11-13 01:28:58

回答

0

請檢查此代碼是否有對稱密鑰加密。您可以重構以適應您的加密方法。

import java.security.AlgorithmParameters; 
import java.security.InvalidAlgorithmParameterException; 
import java.security.InvalidKeyException; 
import java.security.NoSuchAlgorithmException; 
import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.KeyGenerator; 
import javax.crypto.NoSuchPaddingException; 
import javax.crypto.SecretKey; 
import javax.crypto.spec.IvParameterSpec; 
public class SymmEncryption { 
public static void main(String[] args) throws InvalidAlgorithmParameterException { 
    try { 
     KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); 
     keyGenerator.init(256); // 56 is the keysize. Fixed for DES 
     //Initialization Vector 
     byte[] iv = "1234567812345678".getBytes(); 
     IvParameterSpec ivSpec = new IvParameterSpec(iv); 
     SecretKey secretKey = keyGenerator.generateKey(); 
     System.out.println(secretKey.getFormat()); 
     Cipher desCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//algorithm/mode/padding 
     //Electronic Codebook (ECB) 
     System.out.format("Secret Key: %s--%s--%s%n", secretKey.getAlgorithm(), secretKey.getFormat(), secretKey.getEncoded()); 
     // Initialize the cipher for encryption 
     desCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); 
     // sensitive information 
     byte[] text = "No body can see me".getBytes(); 
     System.out.println("Hex text: " + byteArrayToHex(text)); 
     System.out.println("Text [Byte Format] : " + text); 
     System.out.println("Text : " + new String(text)); 
     // Encrypt the text 
     byte[] textEncrypted = desCipher.doFinal(text); 
     System.out.println("Text Encryted : " + textEncrypted); 
     System.out.println("Hex Encrypted text: " + byteArrayToHex(textEncrypted)); 
     // Initialize the same cipher for decryption 
     desCipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); 
     // Decrypt the text 
     byte[] textDecrypted = desCipher.doFinal(textEncrypted); 
     System.out.println("Text Decryted : " + new String(textDecrypted)); 
     System.out.println("Hex Decrypted text: " + byteArrayToHex(textDecrypted)); 
    } catch (NoSuchAlgorithmException e) { 
     e.printStackTrace(); 
    } catch (NoSuchPaddingException e) { 
     e.printStackTrace(); 
    } catch (InvalidKeyException e) { 
     e.printStackTrace(); 
    } catch (IllegalBlockSizeException e) { 
     e.printStackTrace(); 
    } catch (BadPaddingException e) { 
     e.printStackTrace(); 
    } 
} 
static String byteArrayToHex(byte[] a) { 
    StringBuilder sb = new StringBuilder(); 
    for (byte b : a) 
     sb.append(String.format("%02x", b & 0xff)); 
    return sb.toString(); 
} 
} 
-1
/** 
* Creates a cipher for encryption or decryption. 
* 
* @param algorithm PBE algorithm like "PBEWithMD5AndDES" or "PBEWithMD5AndTripleDES". 
* @param mode Encyrption or decyrption. 
* @param password Password 
* @param salt Salt usable with algorithm. 
* @param count Iterations. 
* @return Ready initialized cipher. 
* @throws GeneralSecurityException Error creating the cipher. 
*/ 
private static Cipher createCipher(final String algorithm, final int mode, final char[] password, final byte[] salt, final int count) throws GeneralSecurityException { 
    final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm); 
    final PBEKeySpec keySpec = new PBEKeySpec(password); 
    final SecretKey key = keyFactory.generateSecret(keySpec); 
    final Cipher cipher = Cipher.getInstance(algorithm); 
    final PBEParameterSpec params = new PBEParameterSpec(salt, count); 
    cipher.init(mode, key, params); 
    return cipher; 
} 

/** 
* Encrypts some data based on a password. 
* @param algorithm PBE algorithm like "PBEWithMD5AndDES" or "PBEWithMD5AndTripleDES" 
* @param data Data to encrypt 
* @param password Password 
* @param salt Salt usable with algorithm 
* @param count Iterations. 
* @return Encrypted data. 
*/ 
public static byte[] encryptPasswordBased(final String algorithm, final byte[] data, final char[] password, final byte[] salt, final int count) { 
    Validate.notNull(algorithm); 
    Validate.notNull(data); 
    Validate.notNull(password); 
    Validate.notNull(salt); 
    try { 
     final Cipher cipher = createCipher(algorithm, Cipher.ENCRYPT_MODE, password, salt, count); 
     return cipher.doFinal(data); 
    } catch (final Exception ex) { 
     throw new RuntimeException("Error encrypting the password!", ex); 
    } 
} 

/** 
* Decrypts some data based on a password. 
* @param algorithm PBE algorithm like "PBEWithMD5AndDES" or "PBEWithMD5AndTripleDES" 
* @param encryptedData Data to decrypt 
* @param password Password 
* @param salt Salt usable with algorithm 
* @param count Iterations. 
* @return Encrypted data. 
*/ 
public static byte[] decryptPasswordBased(final String algorithm, final byte[] encryptedData, final char[] password, final byte[] salt, final int count) { 
    Validate.notNull(algorithm); 
    Validate.notNull(encryptedData); 
    Validate.notNull(password); 
    Validate.notNull(salt); 
    try { 
     final Cipher cipher = createCipher(algorithm, Cipher.DECRYPT_MODE, password, salt, count); 
     return cipher.doFinal(encryptedData); 
    } catch (final Exception ex) { 
     throw new RuntimeException("Error decrypting the password!", ex); 
    } 
} 
+0

Obligatory反對票,因爲你只是再次發佈完全相同的代碼。您使用OP不需要/需要的密鑰派生。如果您要發佈代碼,至少需要對其進行編輯以符合問題中確定的約束條件。 – 2014-12-23 16:27:38