Java-对称加密-AES





密码系统模型:

Java-对称加密-AES_第1张图片

常用对称算法:



在对称加密算法中常用的算法有:DES、3DES、TDEA、Blowfish、RC2、RC4、RC5、IDEA、SKIPJACK、AES等。




对称算法AES


Base64Decoder

package com.ding.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
/**
 * 
 * @author daniel
 * @email [email protected]
 * @time 2016-6-11 下午7:39:48
 */
public class Base64Decoder extends FilterInputStream {
	private static final char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
			'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };

	private static final int[] ints = new int[128];
	static {
		for (int i = 0; i < 64; i++) {
			ints[chars[i]] = i;
		}
	}

	private int charCount;
	private int carryOver;

	/***
	 * Constructs a new Base64 decoder that reads input from the given
	 * InputStream.
	 * 
	 * @param in
	 *            the input stream
	 */
	public Base64Decoder(InputStream in) {
		super(in);
	}

	/***
	 * Returns the next decoded character from the stream, or -1 if end of
	 * stream was reached.
	 * 
	 * @return the decoded character, or -1 if the end of the input stream is
	 *         reached
	 * @exception IOException
	 *                if an I/O error occurs
	 */
	public int read() throws IOException {
		// Read the next non-whitespace character
		int x;
		do {
			x = in.read();
			if (x == -1) {
				return -1;
			}
		} while (Character.isWhitespace((char) x));
		charCount++;

		// The '=' sign is just padding
		if (x == '=') {
			return -1; // effective end of stream
		}

		// Convert from raw form to 6-bit form
		x = ints[x];

		// Calculate which character we're decoding now
		int mode = (charCount - 1) % 4;

		// First char save all six bits, go for another
		if (mode == 0) {
			carryOver = x & 63;
			return read();
		}
		// Second char use previous six bits and first two new bits,
		// save last four bits
		else if (mode == 1) {
			int decoded = ((carryOver << 2) + (x >> 4)) & 255;
			carryOver = x & 15;
			return decoded;
		}
		// Third char use previous four bits and first four new bits,
		// save last two bits
		else if (mode == 2) {
			int decoded = ((carryOver << 4) + (x >> 2)) & 255;
			carryOver = x & 3;
			return decoded;
		}
		// Fourth char use previous two bits and all six new bits
		else if (mode == 3) {
			int decoded = ((carryOver << 6) + x) & 255;
			return decoded;
		}
		return -1; // can't actually reach this line
	}

	/***
	 * Reads decoded data into an array of bytes and returns the actual number
	 * of bytes read, or -1 if end of stream was reached.
	 * 
	 * @param buf
	 *            the buffer into which the data is read
	 * @param off
	 *            the start offset of the data
	 * @param len
	 *            the maximum number of bytes to read
	 * @return the actual number of bytes read, or -1 if the end of the input
	 *         stream is reached
	 * @exception IOException
	 *                if an I/O error occurs
	 */
	public int read(byte[] buf, int off, int len) throws IOException {
		if (buf.length < (len + off - 1)) {
			throw new IOException("The input buffer is too small: " + len + " bytes requested starting at offset " + off + " while the buffer " + " is only " + buf.length + " bytes long.");
		}

		// This could of course be optimized
		int i;
		for (i = 0; i < len; i++) {
			int x = read();
			if (x == -1 && i == 0) { // an immediate -1 returns -1
				return -1;
			} else if (x == -1) { // a later -1 returns the chars read so far
				break;
			}
			buf[off + i] = (byte) x;
		}
		return i;
	}

	/***
	 * Returns the decoded form of the given encoded string, as a String. Note
	 * that not all binary data can be represented as a String, so this method
	 * should only be used for encoded String data. Use decodeToBytes()
	 * otherwise.
	 * 
	 * @param encoded
	 *            the string to decode
	 * @return the decoded form of the encoded string
	 */
	public static String decode(String encoded) {
		return new String(decodeToBytes(encoded));
	}

	/***
	 * Returns the decoded form of the given encoded string, as bytes.
	 * 
	 * @param encoded
	 *            the string to decode
	 * @return the decoded form of the encoded string
	 */
	@SuppressWarnings("resource")
	public static byte[] decodeToBytes(String encoded) {
		byte[] bytes = null;
		try {
			bytes = encoded.getBytes("UTF-8");
		} catch (UnsupportedEncodingException ignored) {
		}

		Base64Decoder in = new Base64Decoder(new ByteArrayInputStream(bytes));

		ByteArrayOutputStream out = new ByteArrayOutputStream((int) (bytes.length * 0.67));

		try {
			byte[] buf = new byte[4 * 1024]; // 4K buffer
			int bytesRead;
			while ((bytesRead = in.read(buf)) != -1) {
				out.write(buf, 0, bytesRead);
			}
			out.close();

			return out.toByteArray();
		} catch (IOException ignored) {
			return null;
		}
	}
}


Base64Encoder

package com.ding.test;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
/**
 * 
 * @author daniel
 * @email [email protected]
 * @time 2016-6-11 下午7:39:53
 */
public class Base64Encoder extends FilterOutputStream {
 
	private static final char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
			'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };

	private int charCount;
	private int carryOver;

	/***
	 * Constructs a new Base64 encoder that writes output to the given
	 * OutputStream.
	 * 
	 * @param out
	 *            the output stream
	 */
	public Base64Encoder(OutputStream out) {
		super(out);
	}

	/***
	 * Writes the given byte to the output stream in an encoded form.
	 * 
	 * @exception IOException
	 *                if an I/O error occurs
	 */
	public void write(int b) throws IOException {
		// Take 24-bits from three octets, translate into four encoded chars
		// Break lines at 76 chars
		// If necessary, pad with 0 bits on the right at the end
		// Use = signs as padding at the end to ensure encodedLength % 4 == 0

		// Remove the sign bit,
		// thanks to Christian Schweingruber 
		if (b < 0) {
			b += 256;
		}

		// First byte use first six bits, save last two bits
		if (charCount % 3 == 0) {
			int lookup = b >> 2;
			carryOver = b & 3; // last two bits
			out.write(chars[lookup]);
		}
		// Second byte use previous two bits and first four new bits,
		// save last four bits
		else if (charCount % 3 == 1) {
			int lookup = ((carryOver << 4) + (b >> 4)) & 63;
			carryOver = b & 15; // last four bits
			out.write(chars[lookup]);
		}
		// Third byte use previous four bits and first two new bits,
		// then use last six new bits
		else if (charCount % 3 == 2) {
			int lookup = ((carryOver << 2) + (b >> 6)) & 63;
			out.write(chars[lookup]);
			lookup = b & 63; // last six bits
			out.write(chars[lookup]);
			carryOver = 0;
		}
		charCount++;

		// Add newline every 76 output chars (that's 57 input chars)
		if (charCount % 57 == 0) {
			out.write('\n');
		}
	}

	/***
	 * Writes the given byte array to the output stream in an encoded form.
	 * 
	 * @param buf
	 *            the data to be written
	 * @param off
	 *            the start offset of the data
	 * @param len
	 *            the length of the data
	 * @exception IOException
	 *                if an I/O error occurs
	 */
	public void write(byte[] buf, int off, int len) throws IOException {
		// This could of course be optimized
		for (int i = 0; i < len; i++) {
			write(buf[off + i]);
		}
	}

	/***
	 * Closes the stream, this MUST be called to ensure proper padding is
	 * written to the end of the output stream.
	 * 
	 * @exception IOException
	 *                if an I/O error occurs
	 */
	public void close() throws IOException {
		// Handle leftover bytes
		if (charCount % 3 == 1) { // one leftover
			int lookup = (carryOver << 4) & 63;
			out.write(chars[lookup]);
			out.write('=');
			out.write('=');
		} else if (charCount % 3 == 2) { // two leftovers
			int lookup = (carryOver << 2) & 63;
			out.write(chars[lookup]);
			out.write('=');
		}
		super.close();
	}

	/***
	 * Returns the encoded form of the given unencoded string. The encoder uses
	 * the ISO-8859-1 (Latin-1) encoding to convert the string to bytes. For
	 * greater control over the encoding, encode the string to bytes yourself
	 * and use encode(byte[]).
	 * 
	 * @param unencoded
	 *            the string to encode
	 * @return the encoded form of the unencoded string
	 */
	public static String encode(String unencoded) {
		byte[] bytes = null;
		try {
			bytes = unencoded.getBytes("UTF-8");
		} catch (UnsupportedEncodingException ignored) {
		}
		return encode(bytes);
	}

	/***
	 * Returns the encoded form of the given unencoded string.
	 * 
	 * @param bytes
	 *            the bytes to encode
	 * @return the encoded form of the unencoded string
	 */
	public static String encode(byte[] bytes) {
		ByteArrayOutputStream out = new ByteArrayOutputStream((int) (bytes.length * 1.37));
		Base64Encoder encodedOut = new Base64Encoder(out);

		try {
			encodedOut.write(bytes);
			encodedOut.close();

			return out.toString("UTF-8");
		} catch (IOException ignored) {
			return null;
		}
	}

	public static void main(String[] args) throws Exception {
		if (args.length != 1) {
			System.err.println("Usage: java com.oreilly.servlet.Base64Encoder fileToEncode");
			return;
		}

		Base64Encoder encoder = null;
		BufferedInputStream in = null;
		try {
			encoder = new Base64Encoder(System.out);
			in = new BufferedInputStream(new FileInputStream(args[0]));

			byte[] buf = new byte[4 * 1024]; // 4K buffer
			int bytesRead;
			while ((bytesRead = in.read(buf)) != -1) {
				encoder.write(buf, 0, bytesRead);
			}
		} finally {
			if (in != null)
				in.close();
			if (encoder != null)
				encoder.close();
		}
	}
}


AES

package com.ding.test;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @author daniel
 * @email [email protected]
 * @time 2016-6-11 下午7:32:57
 */
public class AES {
	public static final String KEY_GENERATION_ALG = "PBKDF2WithHmacSHA1";
	public static final int HASH_ITERATIONS = 10000;
	public static final int KEY_LENGTH = 256;
	public static byte[] salt = { 1, 3, 9, 6, 9, 4, 4, 4, 0, 2, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };
	public static final String CIPHERMODEPADDING = "AES/CBC/PKCS5Padding";
	public static SecretKeyFactory keyfactory = null;
	public static IvParameterSpec ivSpec = new IvParameterSpec(new byte[] { 0xA, 1, 0xB, 5, 4, 0xF, 7, 9, 0x17, 3, 1, 6, 8, 0xC, 0xD, 91 });


	public synchronized static void createSecretKeyFactory() {
		if (keyfactory == null) {
			try {
				keyfactory = SecretKeyFactory.getInstance(KEY_GENERATION_ALG);
			} catch (NoSuchAlgorithmException e) {
				System.out.println("no key factory support for PBEWITHSHAANDTWOFISH-CBC");
			}
		}
	}

	public static SecretKeySpec aesKeyConvert(String key) {
		try {
			PBEKeySpec myKeyspec = new PBEKeySpec(key.toCharArray(), salt, HASH_ITERATIONS, KEY_LENGTH);
			if (keyfactory == null)
				createSecretKeyFactory();
			SecretKey sk = keyfactory.generateSecret(myKeyspec);
			byte[] skAsByteArray = sk.getEncoded();
			SecretKeySpec skforAES = new SecretKeySpec(skAsByteArray, "AES");
			return skforAES;
		} catch (InvalidKeySpecException ikse) {
			System.out.println("invalid key spec for PBEWITHSHAANDTWOFISH-CBC");
		}
		return null;
	}

	public static String encrypt(byte[] plaintext, String password) {
		SecretKeySpec skforAES = aesKeyConvert(password);
		byte[] ciphertext = encrypt(CIPHERMODEPADDING, skforAES, ivSpec, plaintext);
		String base64_ciphertext = Base64Encoder.encode(ciphertext);
		return base64_ciphertext;
	}

	public static String decrypt(String ciphertext_base64, String password) {
		byte[] s = Base64Decoder.decodeToBytes(ciphertext_base64);
		SecretKeySpec skforAES = aesKeyConvert(password);
		String decrypted = new String(decrypt(CIPHERMODEPADDING, skforAES, ivSpec, s));
		return decrypted;
	}

	public static String decrypt(byte[] data, String password) {
		SecretKeySpec skforAES = aesKeyConvert(password);
		String decrypted = new String(decrypt(CIPHERMODEPADDING, skforAES, ivSpec, data));
		return decrypted;
	}

	public static byte[] encrypt(String cmp, SecretKey sk, IvParameterSpec IV, byte[] msg) {
		try {
			Cipher c = Cipher.getInstance(cmp);
			c.init(Cipher.ENCRYPT_MODE, sk, IV);
			return c.doFinal(msg);
		} catch (NoSuchAlgorithmException e) {
			System.out.println(e.getMessage());
		} catch (NoSuchPaddingException e) {
			System.out.println(e.getMessage());
		} catch (InvalidKeyException e) {
			System.out.println(e.getMessage());
		} catch (InvalidAlgorithmParameterException e) {
			System.out.println(e.getMessage());
		} catch (IllegalBlockSizeException e) {
			System.out.println(e.getMessage());
		} catch (BadPaddingException e) {
			System.out.println(e.getMessage());
		}
		return null;
	}

	public static byte[] decrypt(String cmp, SecretKey sk, IvParameterSpec IV, byte[] ciphertext) {
		try {
			Cipher c = Cipher.getInstance(cmp);
			c.init(Cipher.DECRYPT_MODE, sk, IV);
			return c.doFinal(ciphertext);
		} catch (NoSuchAlgorithmException nsae) {
			System.out.println(nsae.getMessage());
		} catch (NoSuchPaddingException nspe) {
			System.out.println(nspe.getMessage());
		} catch (InvalidKeyException e) {
			System.out.println(e.getMessage());
		} catch (InvalidAlgorithmParameterException e) {
			System.out.println(e.getMessage());
		} catch (IllegalBlockSizeException e) {
			System.out.println(e.getMessage());
		} catch (BadPaddingException e) {
			System.out.println(e.getMessage());
		}
		return null;
	}
}

测试类


package com.ding.test;
/**
 * 测试类
 * 输出:
 * 原:yuanwen
加密后:pF5lucWGXeeFwmendXQyVA==
解密后:yuanwen

 * 
 * @author daniel
 * @email [email protected]
 * @time 2016-6-11 下午7:51:47
 */
public class Zmain {

	/**
	 * @author daniel
	 * @time 2016-6-11 下午7:48:12
	 * @param args
	 */

 

	public static void main(String[] args) {
		// 加密原文
		String plaintext = "yuanwen";
		// 密钥
		String key = "123456";
		//密文
		String ciphertext;
		try {
			ciphertext = AES.encrypt(plaintext.getBytes("UTF-8"), key);
			String de = AES.decrypt(ciphertext, key);
			System.out.println("原:" + plaintext);
			System.out.println("加密后:" + ciphertext);
			System.out.println("解密后:" + de);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}


输出结果:


Java-对称加密-AES_第2张图片



源码:



https://github.com/dingsai88/StudyTest/tree/master/src/com/ding/util/aes












你可能感兴趣的:(Java-对称加密-AES)