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

时间: 2024-08-28 23:22:31

java之Symmetric encryption techniques的相关文章

java之Secure communication terminology

java之Secure communication terminology There are several terms that are used when working with secure communications. These include the following: Authentication: This is the process of verifying a user or system Authorization: This is the process of

Java Secure Socket Extension (JSSE) Reference Guide

Skip to Content Oracle Technology Network Software Downloads Documentation Search Java Secure Socket Extension (JSSE) Reference Guide This guide covers the following topics: Skip Navigation Links Introduction Features and Benefits JSSE Standard API S

SSL 通信及 java keystore 工具介绍

http://www.javacodegeeks.com/2014/07/java-keystore-tutorial.html Table Of Contents 1. Introduction 2. SSL and how it works 3. Private Keys 4. Public Certificates 5. Root Certificates 6. Certificate Authorities 7. Certificate Chain 8. Keystore using J

java Base64 [ Encode And Decode In Base64 Using Java ]

http://www.javatips.net/blog/2011/08/how-to-encode-and-decode-in-base64-using-java http://commons.apache.org/proper/commons-codec/ 官方下载链接 Encode And Decode In Base64 Using Java explains about different techniques for Encode Base64 using java / Decode

Spring Security Encryption三种加密方式

Encryption One-way encryption       单项加密,客户端将要传递的值先加密(使用特定的加密方法),将原值和加密好的值传递过去,服务器端将原始数据也进行一次加密(两者加密的方法一致),最后匹配连个加密后的值是否相等.相等就通过,否则不通过.   Symmetric encryption     双向,既能加密又能解密. Public key cryptography  公钥和秘钥,公钥向外面公开,秘钥只有自己知道,传输的数据使用公钥加密,得到后使用秘钥解密.

Android Chromium:不成功的尝试,无法从Typeface.java类获得C++ SkTypeface对象

这也就是说,Java Activity层的用户自定义默认字体通过标准framework/JNI的途径是无法传递应用到Chromium内核的. 本来的基本想法是:通过Typeface.DEFAULT获得Java层的系统当前默认字体设置,通过Java动态反射调用获得native_instance句柄,然后尝试用JNI C++代码获得SkTypeface*指针,调用SkTypeface::serialize序列化到一个临时字体文件,然后将此路径回传Java,再重新传到Chromium内核代码. 帖2段

java学习笔记 5

随手 看到了这篇关于Java到底哪里出了问题的文章,笑傻了23333 “Java developers just can’t help themselves it seems - give em an inch, and next thing you know you’re looking at a OO hierarchy 15 layers deep and instantiating a hammer hammer factory.” 继承 Java中的继承用extends,所有的继承都是

httpcomponents-client-4.4.x

Chapter 1. Fundamentals Prev     Next Chapter 1. Fundamentals 1.1. Request execution The most essential function of HttpClient is to execute HTTP methods. Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges, usu

httpcomponents-client-ga(4.5)

Chapter 1. Fundamentals Prev     Next Chapter 1. Fundamentals 1.1. Request execution The most essential function of HttpClient is to execute HTTP methods. Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges, usu