1. 程式人生 > >AES加密解密圖片資源

AES加密解密圖片資源

AES.java

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {
	/*
	 * encrypt key contain 26 letters and digitshere use AES-128-CBC model
	 * length must be 16
	 */
	private static String sKey = "1234567890987654";
	private static String cPriKey = "1122334455667788";

	public static String Encrypt(String sSrc) throws Exception {
		if (sKey == null) {
			System.out.print("Key id null");
			return null;
		}
		// judge whethe Key's length is 16
		if (sKey.length() != 16) {
			System.out.print("Key's length is not 16");
			return null;
		}
		byte[] raw = sKey.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec iv = new IvParameterSpec(cPriKey.getBytes());// use CBC model
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(sSrc.getBytes());

		return Base64.encode(encrypted, 0, encrypted.length);
	}

	public static String Decrypt(String sSrc) throws Exception {
		try {
			if (sKey == null) {
				System.out.print("Key id is null");
				return null;
			}
			// Judge Whethe Key's Length Is 16
			if (sKey.length() != 16) {
				System.out.print("Key's length is not 16");
				return null;
			}
			byte[] raw = sKey.getBytes("ASCII");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec iv = new IvParameterSpec(cPriKey.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			byte[] encrypted1 = Base64.decode(sSrc, 0, sSrc.getBytes().length);
			try {
				byte[] original = cipher.doFinal(encrypted1);
				String originalString = new String(original);
				return originalString;
			} catch (Exception e) {
				System.out.println(e.toString());
				return null;
			}
		} catch (Exception ex) {
			System.out.println(ex.toString());
			return null;
		}
	}

}

Base64.java
import java.io.IOException;

public class Base64 {

	private Base64() {}

	/**
	 * This character array provides the alphabet map from RFC1521.
	 */
	private final static char ALPHABET[] = {
			'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', '+', '/' 
	};

	/**
	 * Decodes a 7 bit Base64 character into its binary value.
	 */
	private static int valueDecoding[] = new int[128];

	/**
	 * initializes the value decoding array from the character map
	 */
	static {
		for (int i = 0; i < valueDecoding.length; i++) {
			valueDecoding[i] = -1;
		}

		for (int i = 0; i < ALPHABET.length; i++) {
			valueDecoding[ALPHABET[i]] = i;
		}
	}

	/**
	 * Converts a byte array into a Base64 encoded string.
	 * 
	 * @param data
	 *            bytes to encode
	 * @param offset
	 *            which byte to start at
	 * @param length
	 *            how many bytes to encode; padding will be added if needed
	 * @return base64 encoding of data; 4 chars for every 3 bytes
	 */
	public static String encode(byte[] data, int offset, int length) {
		int i;
		int encodedLen;
		char[] encoded;

		// 4 chars for 3 bytes, run input up to a multiple of 3
		encodedLen = (length + 2) / 3 * 4;
		encoded = new char[encodedLen];

		for (i = 0, encodedLen = 0; encodedLen < encoded.length; i += 3, encodedLen += 4) {
			encodeQuantum(data, offset + i, length - i, encoded, encodedLen);
		}

		return new String(encoded);
	}

	/**
	 * Encodes 1, 2, or 3 bytes of data as 4 Base64 chars.
	 * 
	 * @param in
	 *            buffer of bytes to encode
	 * @param inOffset
	 *            where the first byte to encode is
	 * @param len
	 *            how many bytes to encode
	 * @param out
	 *            buffer to put the output in
	 * @param outOffset
	 *            where in the output buffer to put the chars
	 */
	private static void encodeQuantum(byte in[], int inOffset, int len,
			char out[], int outOffset) {
		byte a = 0, b = 0, c = 0;

		a = in[inOffset];
		out[outOffset] = ALPHABET[(a >>> 2) & 0x3F];

		if (len > 2) {
			b = in[inOffset + 1];
			c = in[inOffset + 2];
			out[outOffset + 1] = ALPHABET[((a << 4) & 0x30) + ((b >>> 4) & 0xf)];
			out[outOffset + 2] = ALPHABET[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)];
			out[outOffset + 3] = ALPHABET[c & 0x3F];
		} else if (len > 1) {
			b = in[inOffset + 1];
			out[outOffset + 1] = ALPHABET[((a << 4) & 0x30) + ((b >>> 4) & 0xf)];
			out[outOffset + 2] = ALPHABET[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)];
			out[outOffset + 3] = '=';
		} else {
			out[outOffset + 1] = ALPHABET[((a << 4) & 0x30) + ((b >>> 4) & 0xf)];
			out[outOffset + 2] = '=';
			out[outOffset + 3] = '=';
		}
	}

	/**
	 * Converts a Base64 encoded string to a byte array.
	 * 
	 * @param encoded
	 *            Base64 encoded data
	 * @return decode binary data; 3 bytes for every 4 chars - minus padding
	 * @exception IOException
	 *                is thrown, if an I/O error occurs reading the data
	 */
	public static byte[] decode(String encoded) throws IOException {
		return decode(encoded, 0, encoded.length());
	}

	/**
	 * Converts an embedded Base64 encoded string to a byte array.
	 * 
	 * @param encoded
	 *            a String with Base64 data embedded in it
	 * @param offset
	 *            which char of the String to start at
	 * @param length
	 *            how many chars to decode; must be a multiple of 4
	 * @return decode binary data; 3 bytes for every 4 chars - minus padding
	 * @exception IOException
	 *                is thrown, if an I/O error occurs reading the data
	 */
	public static byte[] decode(String encoded, int offset, int length)
			throws IOException {
		int i;
		int decodedLen;
		byte[] decoded;

		// the input must be a multiple of 4
		if (length % 4 != 0) {
			throw new IOException("Base64 string length is not multiple of 4");
		}

		// 4 chars for 3 bytes, but there may have been pad bytes
		decodedLen = length / 4 * 3;
		if (encoded.charAt(offset + length - 1) == '=') {
			decodedLen--;
			if (encoded.charAt(offset + length - 2) == '=') {
				decodedLen--;
			}
		}

		decoded = new byte[decodedLen];
		for (i = 0, decodedLen = 0; i < length; i += 4, decodedLen += 3) {
			decodeQuantum(encoded.charAt(offset + i),
					encoded.charAt(offset + i + 1),
					encoded.charAt(offset + i + 2),
					encoded.charAt(offset + i + 3), decoded, decodedLen);
		}

		return decoded;
	}

	/**
	 * Decode 4 Base64 chars as 1, 2, or 3 bytes of data.
	 * 
	 * @param in1
	 *            first char of quantum to decode
	 * @param in2
	 *            second char of quantum to decode
	 * @param in3
	 *            third char of quantum to decode
	 * @param in4
	 *            forth char of quantum to decode
	 * @param out
	 *            buffer to put the output in
	 * @param outOffset
	 *            where in the output buffer to put the bytes
	 */
	private static void decodeQuantum(char in1, char in2, char in3, char in4,
			byte[] out, int outOffset) throws IOException {
		int a = 0, b = 0, c = 0, d = 0;
		int pad = 0;

		a = valueDecoding[in1 & 127];
		b = valueDecoding[in2 & 127];

		if (in4 == '=') {
			pad++;
			if (in3 == '=') {
				pad++;
			} else {
				c = valueDecoding[in3 & 127];
			}
		} else {
			c = valueDecoding[in3 & 127];
			d = valueDecoding[in4 & 127];
		}

		if (a < 0 || b < 0 || c < 0 || d < 0) {
			throw new IOException("Invalid character in Base64 string");
		}

		// the first byte is the 6 bits of a and 2 bits of b
		out[outOffset] = (byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3));

		if (pad < 2) {
			// the second byte is 4 bits of b and 4 bits of c
			out[outOffset + 1] = (byte) (((b << 4) & 0xf0) | ((c >>> 2) & 0xf));

			if (pad < 1) {
				// the third byte is 2 bits of c and 4 bits of d
				out[outOffset + 2] = (byte) (((c << 6) & 0xc0) | (d & 0x3f));
			}
		}
	}

}

資料處理類:DataTools.java
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class DataTools {

	public static final byte[] InputStreamToByte(InputStream inStream)  
            throws IOException {  
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
        byte[] buff = new byte[100];  
        int rc = 0;  
        while ((rc = inStream.read(buff, 0, 100)) > 0) {  
            swapStream.write(buff, 0, rc);  
        }  
        byte[] in2b = swapStream.toByteArray();  
        return in2b;  
    }
	
	public static String InputStreamTOString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
		} finally {
			try {
				is.close();
			} catch (IOException e) {
			}
		}

		return sb.toString();
	}

	/**
	 * 將String轉換成InputStream
	 * 
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public static InputStream StringTOInputStream(String in) throws Exception {
		ByteArrayInputStream is = new ByteArrayInputStream(
				in.getBytes("ISO-8859-1"));
		return is;
	}

	/**
	 * 將byte陣列轉換成InputStream
	 * 
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public static InputStream byteTOInputStream(byte[] in) throws Exception {
		ByteArrayInputStream is = new ByteArrayInputStream(in);
		return is;
	}

	/**
	 * 將byte陣列轉換成String
	 * 
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public static String byteTOString(byte[] in) throws Exception {
		String string = new String(in, "ISO-8859-1");
		return string;
	}
	
	public static String byteTOString(byte[] in, String type) throws Exception {
		String string = new String(in, type);
		return string;
	}
	
	/***
	 * half-angle Convert to full-angle
	 * 
	 * @param input
	 * @return
	 */
	public static String ToDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}

			if ((c[i] > 65280) && (c[i] < 65375)) {
				c[i] = (char) (c[i] - 65248);
			}
		}
		return new String(c);
	}

}

使用方法:
public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		File file2 = new File("c:\\Users\\zoeice\\Desktop\\111111.png");
		InputStream is = null; 
		BufferedImage bi = null;
		try {
		    bi = ImageIO.read(file2);
		} catch (IOException e) {
		    e.printStackTrace();
		}
		ByteArrayOutputStream bs = new ByteArrayOutputStream();  
        
        ImageOutputStream imOut; 
        try { 
            imOut = ImageIO.createImageOutputStream(bs); 
             
            ImageIO.write(bi, "png",imOut); 
             
            is= new ByteArrayInputStream(bs.toByteArray()); 
             
        } catch (IOException e) { 
            e.printStackTrace(); 
        }  
        System.out.println("原始資料:" + DataTools.InputStreamTOString(is));
		try {
			String str = AES.Encrypt(DataTools.InputStreamTOString(is));
			System.out.println("加密以後:" +str);
			System.out.println("解密以後:"+AES.Decrypt(str));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


相關推薦

AES加密解密圖片資源

AES.java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AES

Aes加密解密

tran delegate class ext str eap ase hfs tde 加密時:先對string進行utf8解析成數組-->對數組進行加密-->對加密結果用base64解析成string。 那麽揭秘時,

AES加密解密&amp;&amp;SHA1、SHA加密&amp;&amp;MD5加密

algorithm buffer password 使用 eas ray locks tex update AES加密解密 SHA1、SHA加密 MD5加密 二話不說立即附上代碼: package com.luo.util; import j

C# 實現 JAVA AES加密解密[原創]

com base gets tran con spec ole tor 技術分享 以下是網上普遍能收到的JAVA AES加密解密方法。 因為裏面用到了KeyGenerator 和 SecureRandom,但是.NET 裏面沒有這2個類。無法使用安全隨機數生成KEY。 我們

AES加密解密 Java中運用

upper span pub substring rac ont wid mem log AES全稱 Advanced Encryption Standard, 高級加密算法,更加安全,可取代DES。 Aes: package com.blog.d201706.en

Javascript實現前端AES加密解密功能

西安人 才網 西安人才網掌握的HTML中的js前端AES加密最近因為項目需求做了一次MITM,俄然即便發現運用HTTPS,也不能確保數據傳輸過程中的安全性。 經過中間人進犯,能夠直接獲取到Http協議的一切內容。 所以開端嘗試做一些簡略的加密,在一定程度上確保安全性。本次選用AES加密數據,所以客戶端

C# 實現AES加密--解密

bsp 密文 rem adding gets manage string sys cipher /// <summary> /// AES 加密 /// </summary> ///

ruby 實現java中的aes 加密解密

abcde class hwm nbsp crypt 實現 () cbc sad def aes_encrypt() cipher = OpenSSL::Cipher::AES.new(128, :CBC) cipher.encrypt cipher.key =

python AES加密解密 pycryptodome

掌握 mod pack 然而 http != col 技術 aes 環境 pyhton3.6 pip 升級到10.0以上,,不然可能出現裝不上的可能。 博主為了解碼 AES 用了1天的時間,安了各種包,然而走了很多坑,在這裏給大家提供一個簡便的方法 首先在命令行(推薦)

Crypto++ AES 加密解密流程

color 程序 pla ESS dem cde inb def 必須 // aesdemo.cpp : 定義控制臺應用程序的入口點。 // #include <stdio.h>#include <tchar.h>#include <ios

php aes加密解密類(兼容php5、php7)

bytes pri rip dom ase lee vat idea cipher <?php /** * @desc:php aes加密解密類 * @author [Lee] <[<[email protected]>]> */ class

java AES 加密解密工具(Advanced Encryption Standard)

@param key block 生成 utf i++ spec res null 1、通用方法 package com.qlkj.hzd.commom.utils; import javax.crypto.*; import java.io.Unsupported

cryptojs aes加密解密

base64和hex vue專案     //如下程式碼寫為vue的全域性函式,便於呼叫     var iv = crypto.enc.Utf8.parse('1234567887654321');    &

PHP使用AES加密/解密

AES加密在php5的版本中使用的mcrypt_decrypt 函式,該函式已經在php7.1後棄用了,取而代之的是openssl的openssl_encrypt和openssl_decrypt,並且程式碼也非常精簡,下面是示例程式碼: class Aes { public $key = ''

CTR分組模式實現AES加密解密(go語言)

版權宣告:本文為作者原創,如需轉載,請註明出處 https://blog.csdn.net/weixin_42940826 AES演算法簡介 AES演算法是為了取代DES演算法而生,雖然3DES演算法仍然可以使用,但是效率比較低下,AES演算法是在眾多演算法中選拔

AES加密解密 附贈 base64

AES加密是一總比較常用的,會補足長度的加密方式,不管你長度為多少,加密完之後都會變成128位(僅指這裡,當然也有其他的AES)。 敲黑板:之前做過一次跨語言的加密解密,發現是不可以的。即java php c++之間不同的加密解密不要通用,因為進位制和編碼的問題,如果強行使用的話。需要二進

使用Python進行AES加密解密功能實現

PyCrypto是一款非常實用的Python加密模組,最近寫了一個檔案加密指令碼需要用到AES加密,和大家分析一下心得。 下載與安裝:PyCrypto專案已經於2015年7月停止了,下面是官方的下載地址。 https://www.dlitz.net/software/pycrypto/ 如果是l

PHP AES加密解密

<?php namespace app\models; class AES{ public $key; //建構函式,用金鑰初始化 function Prpcrypt( $k ) { $this->key = $k; } /*AES加密*/ public static function e

PHP中AES加密解密

我們在工作中會遇到各種加密,下面就是PHP中AES加密解密的類 <?php  class Aes {     /**      * var string&nbs

AES加密/解密字串

高階加密標準(AES,Advanced Encryption Standard)為最常見的對稱加密演算法(微信小程式加密傳輸就是用這個加密演算法的)。對稱加密演算法也就是加密和解密用相同的金鑰,具體的加密流程如下圖:  下面簡單介紹下各個部分的作用與意義: 明文P