码迷,mamicode.com
首页 > 编程语言 > 详细

java之Symmetric encryption techniques

时间:2016-04-16 19:04:05      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://blog.csdn.net/doctor_who2004/article/details/51168408

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!