使用Java中的对称密钥字节[]加密消息

时间:2014-11-09 01:38:58

标签: java encryption cryptography

我想以byte []的形式获取一段纯文本,一个对称密钥(来自先前的计算)并输出密文。 cipherText = encrypt(plainText,sharedSecret) 如何合并纯文本和共享密钥?

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

2 个答案:

答案 0 :(得分: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 :(得分:-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);
    }
}