java之Symmetric encryption techniques

java之Symmetric encryption techniques


Symmetric encryption usesa single key to encrypt and decrypt a message. This type of encryption is classified as either stream ciphers or block ciphers. More details about these algorithms can be found athttps://en.wikipedia.org/wiki/Symmetric-key_algorithm. A provider provides an implementation of an encryption algorithm, and we often choose between them.
Symmetric algorithms that are supported by Java include the following ones where the key size in bits is enclosed in parentheses:
AES (128)
DES (56)
DESede (168)
HmacSHA1
HmacSHA256


Varying lengths of data may be encrypted. Block cipher algorithms are used to handle large blocks of data. There are several block cipher modes of operations, as listed next. We will not detail how these modes work here, but additional information can be found at https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation:
ECB
CBC
CFB
OFB
PCBC

Before we can encrypt or decrypt data, we need a key.

Generating a key

A common way of generating a key is using the KeyGenerator class. There are no public constructors for the class but an overloaded getInstance method will return a KeyGenerator instance. The following example uses the AES algorithm with the default provider. Other versions of this method allow selection of the provider:

KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

The generateKey method returns an instance of an object that implements the SecretKey interface that is shown next. This is the key that is used to support symmetric encryption and decryption:

SecretKey secretKey = keyGenerator.generateKey();

With a key, we can now encrypt data.

Encrypting text using a symmetric key

We will use the following encrypt method in later sections. This method is passed the text
to encrypt and a secret key. The term plain text is frequently used to refer to the 
unencrypted data.
TheCipher class provides the framework for the encryption process. The getInstance method returns an instance of the class where the AES algorithm is used. The Cipher instance is initialized for encryption using Cipher.ENCRYPT_MODE as the first argument, and the secret key as the second argument. The doFinal method encrypts the plain text byte array and returns an encrypted byte array. The Base64 class’s getEncoder returns an encoder that encodes the encrypted bytes。


package com.doctor.ch08;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

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.SecretKeySpec;

/**
 * Symmetric encryption techniques
 * 
 * @author sdcuike
 * 
 *         Created on 2016年4月16日 上午11:18:29
 */
public class SymmetricEncryptionTechniques {

    public static void main(String[] args) throws Throwable {
        String base64Key = generateBase64Key(aes_algorithm);
        System.out.println(base64Key);
        String plainText = "hello doctor ?";
        String encryptToBase64String = encryptToBase64String(plainText, base64Key);
        System.out.println(encryptToBase64String);
        System.out.println(decrpt(encryptToBase64String, base64Key));
    }

    static final String aes_algorithm = "AES";

    static String encryptToBase64String(String plainText, String base64Key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        SecretKey secretKey = getKey(base64Key);
        Cipher cipher = Cipher.getInstance(aes_algorithm);

        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] doFinal = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(doFinal);
    }

    static String decrpt(String encryptedBase64String, String base64Key) throws NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException {
        SecretKey secretKey = getKey(base64Key);
        Cipher cipher = Cipher.getInstance(aes_algorithm);

        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decode = Base64.getDecoder().decode(encryptedBase64String);
        byte[] doFinal = cipher.doFinal(decode);
        return new String(doFinal, StandardCharsets.UTF_8);
    }

    static String generateBase64Key(String encryptionAlgorithm) throws NoSuchAlgorithmException {
        KeyGenerator generator = KeyGenerator.getInstance(encryptionAlgorithm);
        SecretKey secretKey = generator.generateKey();
        byte[] encoded = secretKey.getEncoded();
        return Base64.getEncoder().encodeToString(encoded);
    }

    static SecretKey getKey(String base64Key) throws NoSuchAlgorithmException {
        return new SecretKeySpec(Base64.getDecoder().decode(base64Key), aes_algorithm);
    }
}


IDiyANNH70kdgAW4FJN25g==
mIZ3vpMI07ak37S9ixL2lw==
hello doctor ?


读书笔记:
Learning Network Programming with Java
Copyright © 2015 Packt Publishing

First published: December 2015
Production reference: 1141215
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-547-1
www.packtpub.com

你可能感兴趣的:(java之Symmetric encryption techniques)