AES,MD5,BASE64,Paillier加密算法

1.AES:

import java.security.SecureRandom;   
  
import javax.crypto.Cipher;   
import javax.crypto.KeyGenerator;   
import javax.crypto.SecretKey;   
import javax.crypto.spec.SecretKeySpec;   
  
  
public class AES2Cryption {   
  
    public static String encrypt(String seed, String cleartext) throws Exception {   
        byte[] rawKey = getRawKey(seed.getBytes());   
        byte[] result = encrypt(rawKey, cleartext.getBytes());   
        return toHex(result);   
    }   
       
    public static String decrypt(String seed, String encrypted) throws Exception {   
        byte[] rawKey = getRawKey(seed.getBytes());   
        byte[] enc = toByte(encrypted);   
        byte[] result = decrypt(rawKey, enc);   
        return new String(result);   
    }   
  
    private static byte[] getRawKey(byte[] seed) throws Exception {   
        KeyGenerator kgen = KeyGenerator.getInstance("AES");   
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");   
        sr.setSeed(seed);   
        kgen.init(128, sr); // 192 and 256 bits may not be available   
        SecretKey skey = kgen.generateKey();   
        byte[] raw = skey.getEncoded();   
        return raw;   
    }   
  
       
    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {   
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");   
        Cipher cipher = Cipher.getInstance("AES");   
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);   
        byte[] encrypted = cipher.doFinal(clear);   
        return encrypted;   
    }   
  
    private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {   
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");   
        Cipher cipher = Cipher.getInstance("AES");   
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);   
        byte[] decrypted = cipher.doFinal(encrypted);   
        return decrypted;   
    }   
  
    public static String toHex(String txt) {   
        return toHex(txt.getBytes());   
    }   
    public static String fromHex(String hex) {   
        return new String(toByte(hex));   
    }   
       
    public static byte[] toByte(String hexString) {   
        int len = hexString.length()/2;   
        byte[] result = new byte[len];   
        for (int i = 0; i < len; i++)   
            result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();   
        return result;   
    }   
  
    public static String toHex(byte[] buf) {   
        if (buf == null)   
            return "";   
        StringBuffer result = new StringBuffer(2*buf.length);   
        for (int i = 0; i < buf.length; i++) {   
            appendHex(result, buf[i]);   
        }   
        return result.toString();   
    }   
    private final static String HEX = "0123456789ABCDEF";   
    private static void appendHex(StringBuffer sb, byte b) {   
        sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));   
    }   
       
} 

2.Paillier:

package edu.kxw.encryptionAlgorithm;
/**
 * This program is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for 
 * more details. 
 * 
 * You should have received a copy of the GNU General Public License along with 
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.math.*;
import java.util.*;

/**
 * Paillier Cryptosystem <br><br>
 * References: <br>
 * [1] Pascal Paillier, "Public-Key Cryptosystems Based on Composite Degree Residuosity Classes," EUROCRYPT'99.
 *    URL: <a href="http://www.gemplus.com/smart/rd/publications/pdf/Pai99pai.pdf">http://www.gemplus.com/smart/rd/publications/pdf/Pai99pai.pdf</a><br>
 * 
 * [2] Paillier cryptosystem from Wikipedia. 
 *    URL: <a href="http://en.wikipedia.org/wiki/Paillier_cryptosystem">http://en.wikipedia.org/wiki/Paillier_cryptosystem</a>
 * @author Kun Liu (kunliu1@cs.umbc.edu)
 * @version 1.0
 */
public class Paillier {

    /**
     * p and q are two large primes. 
     * lambda = lcm(p-1, q-1) = (p-1)*(q-1)/gcd(p-1, q-1).
     */
    private BigInteger p,  q,  lambda;
    /**
     * n = p*q, where p and q are two large primes.
     */
    public BigInteger n;
    /**
     * nsquare = n*n
     */
    public BigInteger nsquare;
    /**
     * a random integer in Z*_{n^2} where gcd (L(g^lambda mod n^2), n) = 1.
     */
    private BigInteger g;
    /**
     * number of bits of modulus
     */
    private int bitLength;

    /**
     * Constructs an instance of the Paillier cryptosystem.
     * @param bitLengthVal number of bits of modulus
     * @param certainty The probability that the new BigInteger represents a prime number will exceed (1 - 2^(-certainty)). The execution time of this constructor is proportional to the value of this parameter.
     */
    public Paillier(int bitLengthVal, int certainty) {
        KeyGeneration(bitLengthVal, certainty);
    }

    /**
     * Constructs an instance of the Paillier cryptosystem with 512 bits of modulus and at least 1-2^(-64) certainty of primes generation.
     */
    public Paillier() {
        KeyGeneration(512, 64);
    }

    /**
     * Sets up the public key and private key.
     * @param bitLengthVal number of bits of modulus.
     * @param certainty The probability that the new BigInteger represents a prime number will exceed (1 - 2^(-certainty)). The execution time of this constructor is proportional to the value of this parameter.
     */
    public void KeyGeneration(int bitLengthVal, int certainty) {
        bitLength = bitLengthVal;
        /*Constructs two randomly generated positive BigIntegers that are probably prime, with the specified bitLength and certainty.*/
        p = new BigInteger(bitLength / 2, certainty, new Random());
        q = new BigInteger(bitLength / 2, certainty, new Random());

        n = p.multiply(q);
        nsquare = n.multiply(n);

        g = new BigInteger("2");
        lambda = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)).divide(
                p.subtract(BigInteger.ONE).gcd(q.subtract(BigInteger.ONE)));
        /* check whether g is good.*/
        if (g.modPow(lambda, nsquare).subtract(BigInteger.ONE).divide(n).gcd(n).intValue() != 1) {
            System.out.println("g is not good. Choose g again.");
            System.exit(1);
        }
    }

    /**
     * Encrypts plaintext m. ciphertext c = g^m * r^n mod n^2. This function explicitly requires random input r to help with encryption.
     * @param m plaintext as a BigInteger
     * @param r random plaintext to help with encryption
     * @return ciphertext as a BigInteger
     */
    public BigInteger Encryption(BigInteger m, BigInteger r) {
        return g.modPow(m, nsquare).multiply(r.modPow(n, nsquare)).mod(nsquare);
    }

    /**
     * Encrypts plaintext m. ciphertext c = g^m * r^n mod n^2. This function automatically generates random input r (to help with encryption).
     * @param m plaintext as a BigInteger
     * @return ciphertext as a BigInteger
     */
    public BigInteger Encryption(BigInteger m) {
        BigInteger r = new BigInteger(bitLength, new Random());
        return g.modPow(m, nsquare).multiply(r.modPow(n, nsquare)).mod(nsquare);

    }

    /**
     * Decrypts ciphertext c. plaintext m = L(c^lambda mod n^2) * u mod n, where u = (L(g^lambda mod n^2))^(-1) mod n.
     * @param c ciphertext as a BigInteger
     * @return plaintext as a BigInteger
     */
    public BigInteger Decryption(BigInteger c) {
        BigInteger u = g.modPow(lambda, nsquare).subtract(BigInteger.ONE).divide(n).modInverse(n);
        return c.modPow(lambda, nsquare).subtract(BigInteger.ONE).divide(n).multiply(u).mod(n);
    }

    /**
     * main function
     * @param str intput string
     */
    public static void main(String[] str) {
        /* instantiating an object of Paillier cryptosystem*/
        Paillier paillier = new Paillier();
        /* instantiating two plaintext msgs*/
        BigInteger m1 = new BigInteger("20");
        BigInteger m2 = new BigInteger("60");
        /* encryption*/
        BigInteger em1 = paillier.Encryption(m1);
        BigInteger em2 = paillier.Encryption(m2);
        /* printout encrypted text*/
        System.out.println(em1);
        System.out.println(em2);
        /* printout decrypted text */
        System.out.println(paillier.Decryption(em1).toString());
        System.out.println(paillier.Decryption(em2).toString());

        /* test homomorphic properties -> D(E(m1)*E(m2) mod n^2) = (m1 + m2) mod n */
        BigInteger product_em1em2 = em1.multiply(em2).mod(paillier.nsquare);
        BigInteger sum_m1m2 = m1.add(m2).mod(paillier.n);
        System.out.println("original sum: " + sum_m1m2.toString());
        System.out.println("decrypted sum: " + paillier.Decryption(product_em1em2).toString());

        /* test homomorphic properties -> D(E(m1)^m2 mod n^2) = (m1*m2) mod n */
        BigInteger expo_em1m2 = em1.modPow(m2, paillier.nsquare);
        BigInteger prod_m1m2 = m1.multiply(m2).mod(paillier.n);
        System.out.println("original product: " + prod_m1m2.toString());
        System.out.println("decrypted product: " + paillier.Decryption(expo_em1m2).toString());

    }
}

3.Base64:

/**
 * 
 */
package com.gootrip.util;

/*
 * Base64 encoding and decoding.
 * Copyright (C) 2001-2004 Stephen Ostermiller
 * http://ostermiller.org/contact.pl?regarding=Java+Utilities
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * See COPYING.TXT for details.
 * http://www.jq-school.com
 */

import java.io.*;
import gnu.getopt.*;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.Locale;

/**
 * Implements Base64 encoding and decoding as defined by RFC 2045: "Multipurpose Internet
 * Mail Extensions (MIME) Part One: Format of Internet Message Bodies" page 23.
 * More information about this class is available from <a target="_top" href=
 * "http://ostermiller.org/utils/Base64.html">ostermiller.org</a>.
 *
 * <blockquote>
 * <p>The Base64 Content-Transfer-Encoding is designed to represent
 * arbitrary sequences of octets in a form that need not be humanly
 * readable.  The encoding and decoding algorithms are simple, but the
 * encoded data are consistently only about 33 percent larger than the
 * unencoded data.  This encoding is virtually identical to the one used
 * in Privacy Enhanced Mail (PEM) applications, as defined in RFC 1421.</p>
 *
 * <p>A 65-character subset of US-ASCII is used, enabling 6 bits to be
 * represented per printable character. (The extra 65th character, "=",
 * is used to signify a special processing function.)</p>
 *
 * <p>NOTE:  This subset has the important property that it is represented
 * identically in all versions of ISO 646, including US-ASCII, and all
 * characters in the subset are also represented identically in all
 * versions of EBCDIC. Other popular encodings, such as the encoding
 * used by the uuencode utility, Macintosh binhex 4.0 [RFC-1741], and
 * the base85 encoding specified as part of Level 2 PostScript, do no
 * share these properties, and thus do not fulfill the portability
 * requirements a binary transport encoding for mail must meet.</p>
 *
 * <p>The encoding process represents 24-bit groups of input bits as output
 * strings of 4 encoded characters.  Proceeding from left to right, a
 * 24-bit input group is formed by concatenating 3 8bit input groups.
 * These 24 bits are then treated as 4 concatenated 6-bit groups, each
 * of which is translated into a single digit in the base64 alphabet.
 * When encoding a bit stream via the base64 encoding, the bit stream
 * must be presumed to be ordered with the most-significant-bit first.
 * That is, the first bit in the stream will be the high-order bit in
 * the first 8bit byte, and the eighth bit will be the low-order bit in
 * the first 8bit byte, and so on.</p>
 *
 * <p>Each 6-bit group is used as an index into an array of 64 printable
 * characters.  The character referenced by the index is placed in the
 * output string.  These characters, identified in Table 1, below, are
 * selected so as to be universally representable, and the set excludes
 * characters with particular significance to SMTP (e.g., ".", CR, LF)
 * and to the multipart boundary delimiters defined in RFC 2046 (e.g.,
 * "-").</p>
 * <pre>
 *                  Table 1: The Base64 Alphabet
 *
 *   Value Encoding  Value Encoding  Value Encoding  Value Encoding
 *       0 A            17 R            34 i            51 z
 *       1 B            18 S            35 j            52 0
 *       2 C            19 T            36 k            53 1
 *       3 D            20 U            37 l            54 2
 *       4 E            21 V            38 m            55 3
 *       5 F            22 W            39 n            56 4
 *       6 G            23 X            40 o            57 5
 *       7 H            24 Y            41 p            58 6
 *       8 I            25 Z            42 q            59 7
 *       9 J            26 a            43 r            60 8
 *      10 K            27 b            44 s            61 9
 *      11 L            28 c            45 t            62 +
 *      12 M            29 d            46 u            63 /
 *      13 N            30 e            47 v
 *      14 O            31 f            48 w         (pad) =
 *      15 P            32 g            49 x
 *      16 Q            33 h            50 y
 * </pre>
 * <p>The encoded output stream must be represented in lines of no more
 * than 76 characters each.  All line breaks or other characters no
 * found in Table 1 must be ignored by decoding software.  In base64
 * data, characters other than those in Table 1, line breaks, and other
 * white space probably indicate a transmission error, about which a
 * warning message or even a message rejection might be appropriate
 * under some circumstances.</p>
 *
 * <p>Special processing is performed if fewer than 24 bits are available
 * at the end of the data being encoded.  A full encoding quantum is
 * always completed at the end of a body.  When fewer than 24 input bits
 * are available in an input group, zero bits are added (on the right)
 * to form an integral number of 6-bit groups.  Padding at the end of
 * the data is performed using the "=" character.  Since all base64
 * input is an integral number of octets, only the following cases can
 * arise: (1) the final quantum of encoding input is an integral
 * multiple of 24 bits; here, the final unit of encoded output will be
 * an integral multiple of 4 characters with no "=" padding, (2) the
 * final quantum of encoding input is exactly 8 bits; here, the final
 * unit of encoded output will be two characters followed by two "="
 * padding characters, or (3) the final quantum of encoding input is
 * exactly 16 bits; here, the final unit of encoded output will be three
 * characters followed by one "=" padding character.</p>
 *
 * <p>Because it is used only for padding at the end of the data, the
 * occurrence of any "=" characters may be taken as evidence that the
 * end of the data has been reached (without truncation in transit).  No
 * such assurance is possible, however, when the number of octets
 * transmitted was a multiple of three and no "=" characters are
 * present.</p>
 *
 * <p>Any characters outside of the base64 alphabet are to be ignored in
 * base64-encoded data.</p>
 *
 * <p>Care must be taken to use the proper octets for line breaks if base64
 * encoding is applied directly to text material that has not been
 * converted to canonical form.  In particular, text line breaks must be
 * converted into CRLF sequences prior to base64 encoding.  The
 * important thing to note is that this may be done directly by the
 * encoder rather than in a prior canonization step in some
 * implementations.</p>
 *
 * <p>NOTE: There is no need to worry about quoting potential boundary
 * delimiters within base64-encoded bodies within multipart entities
 * because no hyphen characters are used in the base64 encoding.</p>
 * </blockquote>
 *
 * @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
 * @since ostermillerutils 1.00.00
 */
public class Base64 {

	/**
	 * Symbol that represents the end of an input stream
	 *
	 * @since ostermillerutils 1.00.00
	 */
	private static final int END_OF_INPUT = -1;

	/**
	 * A character that is not a valid base 64 character.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	private static final int NON_BASE_64 = -1;

	/**
	 * A character that is not a valid base 64 character.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	private static final int NON_BASE_64_WHITESPACE = -2;

	/**
	 * A character that is not a valid base 64 character.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	private static final int NON_BASE_64_PADDING = -3;

	/**
	 * This class need not be instantiated, all methods are static.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	private Base64(){
	}

	/**
	 * Table of the sixty-four characters that are used as
	 * the Base64 alphabet: [A-Za-z0-9+/]
	 *
	 * @since ostermillerutils 1.00.00
	 */
	protected static final byte[] base64Chars = {
		'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','+','/',
	};

	/**
	 * Reverse lookup table for the Base64 alphabet.
	 * reversebase64Chars[byte] gives n for the nth Base64
	 * character or negative if a character is not a Base64 character.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	protected static final byte[] reverseBase64Chars = new byte[0x100];
	static {
		// Fill in NON_BASE_64 for all characters to start with
		for (int i=0; i<reverseBase64Chars.length; i++){
			reverseBase64Chars[i] = NON_BASE_64;
		}
		// For characters that are base64Chars, adjust
		// the reverse lookup table.
		for (byte i=0; i < base64Chars.length; i++){
			reverseBase64Chars[base64Chars[i]] = i;
		}
		reverseBase64Chars[' '] = NON_BASE_64_WHITESPACE;
		reverseBase64Chars['\n'] = NON_BASE_64_WHITESPACE;
		reverseBase64Chars['\r'] = NON_BASE_64_WHITESPACE;
		reverseBase64Chars['\t'] = NON_BASE_64_WHITESPACE;
		reverseBase64Chars['\f'] = NON_BASE_64_WHITESPACE;
		reverseBase64Chars['='] = NON_BASE_64_PADDING;
	}

	/**
	 * Version number of this program
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static final String version = "1.2";

	/**
	 * Locale specific strings displayed to the user.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	protected static ResourceBundle labels = ResourceBundle.getBundle("com.Ostermiller.util.Base64",  Locale.getDefault());

	private static final int ACTION_GUESS = 0;
	private static final int ACTION_ENCODE = 1;
	private static final int ACTION_DECODE = 2;

	private static final int ARGUMENT_GUESS = 0;
	private static final int ARGUMENT_STRING = 1;
	private static final int ARGUMENT_FILE = 2;

	/**
	 * Converts the line ending on files, or standard input.
	 * Run with --help argument for more information.
	 *
	 * @param args Command line arguments.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void main(String[] args){
		// create the command line options that we are looking for
		LongOpt[] longopts = {
			new LongOpt(labels.getString("help.option"), LongOpt.NO_ARGUMENT, null, 1),
			new LongOpt(labels.getString("version.option"), LongOpt.NO_ARGUMENT, null, 2),
			new LongOpt(labels.getString("about.option"), LongOpt.NO_ARGUMENT, null, 3),
			new LongOpt(labels.getString("encode.option"), LongOpt.NO_ARGUMENT, null, 'e'),
			new LongOpt(labels.getString("lines.option"), LongOpt.NO_ARGUMENT, null, 'l'),
			new LongOpt(labels.getString("nolines.option"), LongOpt.NO_ARGUMENT, null, 6),
			new LongOpt(labels.getString("decode.option"), LongOpt.NO_ARGUMENT, null, 'd'),
			new LongOpt(labels.getString("decodeall.option"), LongOpt.NO_ARGUMENT, null, 'a'),
			new LongOpt(labels.getString("decodegood.option"), LongOpt.NO_ARGUMENT, null, 5),
			new LongOpt(labels.getString("guess.option"), LongOpt.NO_ARGUMENT, null, 'g'),
			new LongOpt(labels.getString("ext.option"), LongOpt.OPTIONAL_ARGUMENT, null, 'x'),
			new LongOpt(labels.getString("force.option"), LongOpt.NO_ARGUMENT, null, 'f'),
			new LongOpt(labels.getString("quiet.option"), LongOpt.NO_ARGUMENT, null, 'q'),
			new LongOpt(labels.getString("reallyquiet.option"), LongOpt.NO_ARGUMENT, null, 'Q'),
			new LongOpt(labels.getString("verbose.option"), LongOpt.NO_ARGUMENT, null, 'v'),
			new LongOpt(labels.getString("noforce.option"), LongOpt.NO_ARGUMENT, null, 4),
			new LongOpt(labels.getString("file.option"), LongOpt.NO_ARGUMENT, null, 7),
			new LongOpt(labels.getString("string.option"), LongOpt.NO_ARGUMENT, null, 8),
			new LongOpt(labels.getString("newline.option"), LongOpt.NO_ARGUMENT, null, 'n'),
			new LongOpt(labels.getString("nonewline.option"), LongOpt.NO_ARGUMENT, null, 9),
		};
		String oneLetterOptions = "eldagx::fqQvVn";
		Getopt opts = new Getopt(labels.getString("base64"), args, oneLetterOptions, longopts);
		int action = ACTION_GUESS;
		String extension = "base64";
		boolean force = false;
		boolean printMessages = true;
		boolean printErrors = true;
		boolean forceDecode = false;
		boolean lineBreaks = true;
		int argumentType = ARGUMENT_GUESS;
		boolean decodeEndLine = false;
		int c;
		while ((c = opts.getopt()) != -1){
			switch(c){
					case 1:{
					// print out the help message
					String[] helpFlags = new String[]{
						"--" + labels.getString("help.option"),
						"--" + labels.getString("version.option"),
						"--" + labels.getString("about.option"),
						"-g --" + labels.getString("guess.option"),
						"-e --" + labels.getString("encode.option"),
						"-l --" + labels.getString("lines.option"),
						"--" + labels.getString("nolines.option"),
						"-d --" + labels.getString("decode.option"),
						"-a --" + labels.getString("decodeall.option"),
						"--" + labels.getString("decodegood.option"),
						"-x --" + labels.getString("ext.option") + " <" + labels.getString("ext.option") + ">",
						"-f --" + labels.getString("force.option"),
						"--" + labels.getString("noforce.option"),
						"-v --" + labels.getString("verbose.option"),
						"-q --" + labels.getString("quiet.option"),
						"-Q --" + labels.getString("reallyquiet.option"),
						"--" + labels.getString("file.option"),
						"--" + labels.getString("string.option"),
						"-n --" + labels.getString("newline.option"),
						"--" + labels.getString("nonewline.option"),
					};
					int maxLength = 0;
					for (int i=0; i<helpFlags.length; i++){
						maxLength = Math.max(maxLength, helpFlags[i].length());
					}
					maxLength += 2;
					System.out.println(
						labels.getString("base64") + " [-" + StringHelper.replace(oneLetterOptions, ":", "") + "] <" + labels.getString("files") + ">\n" +
						labels.getString("purpose.message") + "\n" +
						"  " + labels.getString("stdin.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[0] ,maxLength, ' ') + labels.getString("help.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[1] ,maxLength, ' ') + labels.getString("version.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[2] ,maxLength, ' ') + labels.getString("about.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[3] ,maxLength, ' ') + labels.getString("g.message") + " (" + labels.getString("default") + ")\n" +
						"  " + StringHelper.postpad(helpFlags[4] ,maxLength, ' ') + labels.getString("e.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[5] ,maxLength, ' ') + labels.getString("l.message") + " (" + labels.getString("default") + ")\n" +
						"  " + StringHelper.postpad(helpFlags[6] ,maxLength, ' ') + labels.getString("nolines.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[7] ,maxLength, ' ') + labels.getString("d.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[8] ,maxLength, ' ') + labels.getString("a.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[9] ,maxLength, ' ') + labels.getString("decodegood.message") + " (" + labels.getString("default") + ")\n" +
						"  " + StringHelper.postpad(helpFlags[10] ,maxLength, ' ') + labels.getString("x.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[11] ,maxLength, ' ') + labels.getString("f.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[12] ,maxLength, ' ') + labels.getString("noforce.message") + " (" + labels.getString("default") + ")\n" +
						"  " + StringHelper.postpad(helpFlags[13] ,maxLength, ' ') + labels.getString("v.message") + " (" + labels.getString("default") + ")\n" +
						"  " + StringHelper.postpad(helpFlags[14] ,maxLength, ' ') + labels.getString("q.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[15] ,maxLength, ' ') + labels.getString("Q.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[16] ,maxLength, ' ') + labels.getString("file.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[17] ,maxLength, ' ') + labels.getString("string.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[18] ,maxLength, ' ') + labels.getString("newline.message") + "\n" +
						"  " + StringHelper.postpad(helpFlags[19] ,maxLength, ' ') + labels.getString("nonewline.message") + "\n"
					);
					System.exit(0);
				} break;
				case 2:{
					// print out the version message
					System.out.println(MessageFormat.format(labels.getString("version"), (Object[])new String[] {version}));
					System.exit(0);
				} break;
				case 3:{
					System.out.println(
						labels.getString("base64") + " -- " + labels.getString("purpose.message") + "\n" +
						MessageFormat.format(labels.getString("copyright"), (Object[])new String[] {"2001-2002", "Stephen Ostermiller (http://ostermiller.org/contact.pl?regarding=Java+Utilities)"}) + "\n\n" +
						labels.getString("license")
					);
					System.exit(0);
				} break;
				case 'd':{
					action = ACTION_DECODE;
				} break;
				case 'a':{
					forceDecode = true;
				} break;
				case 5:{
					forceDecode = false;
				} break;
				case 'e':{
					action = ACTION_ENCODE;
				} break;
				case 'l':{
					lineBreaks = true;
				} break;
				case 6:{
					lineBreaks = false;
				} break;
				case 'g':{
					action = ACTION_GUESS;
				} break;
				case 'x':{
					extension = opts.getOptarg();
					if (extension == null) extension = "";
				} break;
				case 'f':{
					force = true;
				} break;
				case 4:{
					force = false;
				} break;
				case 'v':{
					printMessages = true;
					printErrors = true;
				} break;
				case 'q':{
					printMessages = false;
					printErrors = true;
				} break;
				case 'Q':{
					printMessages = false;
					printErrors = false;
				} break;
				case 7: {
					argumentType = ARGUMENT_FILE;
				} break;
				case 8: {
					argumentType = ARGUMENT_STRING;
				} break;
				case 'n': {
					decodeEndLine = true;
				} break;
				case 9: {
					decodeEndLine = false;
				} break;
				default:{
					System.err.println(labels.getString("unknownarg"));
					System.exit(1);
				}
			}
		}

		int exitCond = 0;
		boolean done = false;
		for (int i=opts.getOptind(); i<args.length; i++){
			done = true;
			File source = new File(args[i]);
			if (argumentType == ARGUMENT_STRING || (argumentType == ARGUMENT_GUESS && !source.exists())){
				try {
					int fileAction = action;
					if (fileAction == ACTION_GUESS){
						if (isBase64(args[i])){
							fileAction = ACTION_DECODE;
						} else {
							fileAction = ACTION_ENCODE;
						}
					}
					if (fileAction == ACTION_ENCODE){
						if (printMessages){
							System.out.println(labels.getString("encodingarg"));
						}
						encode(new ByteArrayInputStream(args[i].getBytes()), System.out, lineBreaks);
					} else {
						if (printMessages){
							System.out.println(labels.getString("decodingarg"));
						}
						decode(new ByteArrayInputStream(args[i].getBytes()), System.out, !forceDecode);
						if (decodeEndLine) System.out.println();
					}
				} catch (Base64DecodingException x){
					if(printErrors){
						System.err.println(args[i] + ": " + x.getMessage() + " " + labels.getString("unexpectedcharforce"));
					}
					exitCond = 1;
				} catch (IOException x){
					if(printErrors){
						System.err.println(args[i] + ": " + x.getMessage());
					}
					exitCond = 1;
				}
			} else 	if (!source.exists()){
				if(printErrors){
					System.err.println(MessageFormat.format(labels.getString("doesnotexist"), (Object[])new String[] {args[i]}));
				}
				exitCond = 1;
			} else if (!source.canRead()){
				if(printErrors){
					System.err.println(MessageFormat.format(labels.getString("cantread"), (Object[])new String[] {args[i]}));
				}
				exitCond = 1;
			} else {
				try {
					int fileAction = action;
					if (fileAction == ACTION_GUESS){
						if (isBase64(source)){
							fileAction = ACTION_DECODE;
						} else {
							fileAction = ACTION_ENCODE;
						}
					}
					String outName = args[i];
					if (extension.length() > 0){
						if (fileAction == ACTION_ENCODE){
							outName = args[i] + "." + extension;
						} else {
							if (args[i].endsWith("." + extension)){
								outName = args[i].substring(0, args[i].length() - (extension.length() + 1));
							}
						}
					}
					File outFile = new File(outName);
					if (!force && outFile.exists()){
						if(printErrors){
							System.err.println(MessageFormat.format(labels.getString("overwrite"), (Object[])new String[] {outName}));
						}
						exitCond = 1;
					} else if (!(outFile.exists() || outFile.createNewFile()) || !outFile.canWrite()){
						if(printErrors){
							System.err.println(MessageFormat.format(labels.getString("cantwrite"), (Object[])new String[] {outName}));
						}
						exitCond = 1;
					} else {
						if (fileAction == ACTION_ENCODE){
							if (printMessages){
								System.out.println(MessageFormat.format(labels.getString("encoding"), (Object[])new String[] {args[i], outName}));
							}
							encode(source, outFile, lineBreaks);
						} else {
							if (printMessages){
								System.out.println(MessageFormat.format(labels.getString("decoding"), (Object[])new String[] {args[i], outName}));
							}
							decode(source, outFile, !forceDecode);
						}
					}
				} catch (Base64DecodingException x){
					if(printErrors){
						System.err.println(args[i] + ": " + x.getMessage() + " " + labels.getString("unexpectedcharforce"));
					}
					exitCond = 1;
				} catch (IOException x){
					if(printErrors){
						System.err.println(args[i] + ": " + x.getMessage());
					}
					exitCond = 1;
				}
			}
		}
		if (!done){
			try {
				if (action == ACTION_GUESS){
					if(printErrors){
						System.err.println(labels.getString("cantguess"));
					}
					exitCond = 1;
				} else if (action == ACTION_ENCODE){
					encode(
						new BufferedInputStream(System.in),
						new BufferedOutputStream(System.out),
						lineBreaks
					);
				} else {
					decode(
						new BufferedInputStream(System.in),
						new BufferedOutputStream(System.out),
						!forceDecode
					);
					if (decodeEndLine) System.out.println();
				}
			} catch (Base64DecodingException x){
				if(printErrors){
					System.err.println(x.getMessage() + " " + labels.getString("unexpectedcharforce"));
				}
				exitCond = 1;
			} catch (IOException x){
				if(printErrors){
					System.err.println(x.getMessage());
				}
				exitCond = 1;
			}
		}
		System.exit(exitCond);
	}

	/**
	 * Encode a String in Base64.
	 * The String is converted to and from bytes according to the platform's
	 * default character encoding.
	 * No line breaks or other white space are inserted into the encoded data.
	 *
	 * @param string The data to encode.
	 * @return An encoded String.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static String encode(String string){
		return new String(encode(string.getBytes()));
	}

	/**
	 * Encode a String in Base64.
	 * No line breaks or other white space are inserted into the encoded data.
	 *
	 * @param string The data to encode.
	 * @param enc Character encoding to use when converting to and from bytes.
	 * @throws UnsupportedEncodingException if the character encoding specified is not supported.
	 * @return An encoded String.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static String encode(String string, String enc) throws UnsupportedEncodingException {
		return new String(encode(string.getBytes(enc)), enc);
	}

	/**
	 * Encode bytes in Base64.
	 * No line breaks or other white space are inserted into the encoded data.
	 *
	 * @param bytes The data to encode.
	 * @return String with Base64 encoded data.
	 *
	 * @since ostermillerutils 1.04.00
	 */
	public static String encodeToString(byte[] bytes){
		return encodeToString(bytes, false);
	}

	/**
	 * Encode bytes in Base64.
	 *
	 * @param bytes The data to encode.
	 * @param lineBreaks  Whether to insert line breaks every 76 characters in the output.
	 * @return String with Base64 encoded data.
	 *
	 * @since ostermillerutils 1.04.00
	 */
	public static String encodeToString(byte[] bytes, boolean lineBreaks){
		try {
			return new String(encode(bytes, lineBreaks), "ASCII");
		} catch (UnsupportedEncodingException iex){
			// ASCII should be supported
			throw new RuntimeException(iex);
		}
	}

	/**
	 * Encode bytes in Base64.
	 * No line breaks or other white space are inserted into the encoded data.
	 *
	 * @param bytes The data to encode.
	 * @return Encoded bytes.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static byte[] encode(byte[] bytes){
		return encode(bytes, false);
	}

	/**
	 * Encode bytes in Base64.
	 *
	 * @param bytes The data to encode.
	 * @param lineBreaks  Whether to insert line breaks every 76 characters in the output.
	 * @return Encoded bytes.
	 *
	 * @since ostermillerutils 1.04.00
	 */
	public static byte[] encode(byte[] bytes, boolean lineBreaks){
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		// calculate the length of the resulting output.
		// in general it will be 4/3 the size of the input
		// but the input length must be divisible by three.
		// If it isn't the next largest size that is divisible
		// by three is used.
		int mod;
		int length = bytes.length;
		if ((mod = length % 3) != 0){
			length += 3 - mod;
		}
		length = length * 4 / 3;
		ByteArrayOutputStream out = new ByteArrayOutputStream(length);
		try {
			encode(in, out, lineBreaks);
		} catch (IOException x){
			// This can't happen.
			// The input and output streams were constructed
			// on memory structures that don't actually use IO.
			throw new RuntimeException(x);
		}
		return out.toByteArray();
	}

	/**
	 * Encode this file in Base64.
	 * Line breaks will be inserted every 76 characters.
	 *
	 * @param fIn File to be encoded (will be overwritten).
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void encode(File fIn) throws IOException {
		encode(fIn, fIn, true);
	}

	/**
	 * Encode this file in Base64.
	 *
	 * @param fIn File to be encoded (will be overwritten).
	 * @param lineBreaks  Whether to insert line breaks every 76 characters in the output.
	 * @throws IOException if an input or output error occurs.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void encode(File fIn, boolean lineBreaks) throws IOException {
		encode(fIn, fIn, lineBreaks);
	}

	/**
	 * Encode this file in Base64.
	 * Line breaks will be inserted every 76 characters.
	 *
	 * @param fIn File to be encoded.
	 * @param fOut File to which the results should be written (may be the same as fIn).
	 * @throws IOException if an input or output error occurs.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void encode(File fIn, File fOut) throws IOException {
		encode(fIn, fOut, true);
	}

	/**
	 * Encode this file in Base64.
	 *
	 * @param fIn File to be encoded.
	 * @param fOut File to which the results should be written (may be the same as fIn).
	 * @param lineBreaks  Whether to insert line breaks every 76 characters in the output.
	 * @throws IOException if an input or output error occurs.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void encode(File fIn, File fOut, boolean lineBreaks) throws IOException {
		File temp = null;
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(fIn));
			temp = File.createTempFile("Base64", null, null);
			out = new BufferedOutputStream(new FileOutputStream(temp));
			encode(in, out, lineBreaks);
			in.close();
			in = null;
			out.flush();
			out.close();
			out = null;
			FileHelper.move(temp, fOut, true);
		} finally {
			if (in != null){
				in.close();
				in = null;
			}
			if (out != null){
				out.flush();
				out.close();
				out = null;
			}
		}
	}

	/**
	 * Encode data from the InputStream to the OutputStream in Base64.
	 * Line breaks are inserted every 76 characters in the output.
	 *
	 * @param in Stream from which to read data that needs to be encoded.
	 * @param out Stream to which to write encoded data.
	 * @throws IOException if there is a problem reading or writing.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void encode(InputStream in, OutputStream out) throws IOException {
		encode(in, out, true);
	}

	/**
	 * Encode data from the InputStream to the OutputStream in Base64.
	 *
	 * @param in Stream from which to read data that needs to be encoded.
	 * @param out Stream to which to write encoded data.
	 * @param lineBreaks Whether to insert line breaks every 76 characters in the output.
	 * @throws IOException if there is a problem reading or writing.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void encode(InputStream in, OutputStream out, boolean lineBreaks) throws IOException {
		// Base64 encoding converts three bytes of input to
		// four bytes of output
		int[] inBuffer = new int[3];
		int lineCount = 0;

		boolean done = false;
		while (!done && (inBuffer[0] = in.read()) != END_OF_INPUT){
			// Fill the buffer
			inBuffer[1] = in.read();
			inBuffer[2] = in.read();

			// Calculate the out Buffer
			// The first byte of our in buffer will always be valid
			// but we must check to make sure the other two bytes
			// are not END_OF_INPUT before using them.
			// The basic idea is that the three bytes get split into
			// four bytes along these lines:
			//      [AAAAAABB] [BBBBCCCC] [CCDDDDDD]
			// [xxAAAAAA] [xxBBBBBB] [xxCCCCCC] [xxDDDDDD]
			// bytes are considered to be zero when absent.
			// the four bytes are then mapped to common ASCII symbols

			// A's: first six bits of first byte
			out.write(base64Chars[ inBuffer[0] >> 2 ]);
			if (inBuffer[1] != END_OF_INPUT){
				// B's: last two bits of first byte, first four bits of second byte
				out.write(base64Chars [(( inBuffer[0] << 4 ) & 0x30) | (inBuffer[1] >> 4) ]);
				if (inBuffer[2] != END_OF_INPUT){
					// C's: last four bits of second byte, first two bits of third byte
					out.write(base64Chars [((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6) ]);
					// D's: last six bits of third byte
					out.write(base64Chars [inBuffer[2] & 0x3F]);
				} else {
					// C's: last four bits of second byte
					out.write(base64Chars [((inBuffer[1] << 2) & 0x3c)]);
					// an equals sign for a character that is not a Base64 character
					out.write('=');
					done = true;
				}
			} else {
				// B's: last two bits of first byte
				out.write(base64Chars [(( inBuffer[0] << 4 ) & 0x30)]);
				// an equal signs for characters that is not a Base64 characters
				out.write('=');
				out.write('=');
				done = true;
			}
			lineCount += 4;
			if (lineBreaks && lineCount >= 76){
				out.write('\n');
				lineCount = 0;
			}
		}
		if (lineBreaks && lineCount >= 1){
			out.write('\n');
			lineCount = 0;
		}
		out.flush();
	}

	/**
	 * Decode a Base64 encoded String.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 * The String is converted to and from bytes according to the platform's
	 * default character encoding.
	 *
	 * @param string The data to decode.
	 * @return A decoded String.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static String decode(String string){
		return new String(decode(string.getBytes()));
	}

	/**
	 * Decode a Base64 encoded String.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param string The data to decode.
	 * @param enc Character encoding to use when converting to and from bytes.
	 * @throws UnsupportedEncodingException if the character encoding specified is not supported.
	 * @return A decoded String.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static String decode(String string, String enc) throws UnsupportedEncodingException {
		return new String(decode(string.getBytes(enc)), enc);
	}

	/**
	 * Decode a Base64 encoded String.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param string The data to decode.
	 * @param encIn Character encoding to use when converting input to bytes (should not matter because Base64 data is designed to survive most character encodings)
	 * @param encOut Character encoding to use when converting decoded bytes to output.
	 * @throws UnsupportedEncodingException if the character encoding specified is not supported.
	 * @return A decoded String.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static String decode(String string, String encIn, String encOut) throws UnsupportedEncodingException {
		return new String(decode(string.getBytes(encIn)), encOut);
	}

	/**
	 * Decode a Base64 encoded String.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 * The String is converted to and from bytes according to the platform's
	 * default character encoding.
	 *
	 * @param string The data to decode.
	 * @return A decoded String.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static String decodeToString(String string){
		return new String(decode(string.getBytes()));
	}

	/**
	 * Decode a Base64 encoded String.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param string The data to decode.
	 * @param enc Character encoding to use when converting to and from bytes.
	 * @throws UnsupportedEncodingException if the character encoding specified is not supported.
	 * @return A decoded String.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static String decodeToString(String string, String enc) throws UnsupportedEncodingException {
		return new String(decode(string.getBytes(enc)), enc);
	}

	/**
	 * Decode a Base64 encoded String.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param string The data to decode.
	 * @param encIn Character encoding to use when converting input to bytes (should not matter because Base64 data is designed to survive most character encodings)
	 * @param encOut Character encoding to use when converting decoded bytes to output.
	 * @throws UnsupportedEncodingException if the character encoding specified is not supported.
	 * @return A decoded String.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static String decodeToString(String string, String encIn, String encOut) throws UnsupportedEncodingException {
		return new String(decode(string.getBytes(encIn)), encOut);
	}

	/**
	 * Decode a Base64 encoded String to an OutputStream.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 * The String is converted from bytes according to the platform's
	 * default character encoding.
	 *
	 * @param string The data to decode.
	 * @param out Stream to which to write decoded data.
	 * @throws IOException if an IO error occurs.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static void decodeToStream(String string, OutputStream out) throws IOException {
		decode(new ByteArrayInputStream(string.getBytes()), out);
	}

	/**
	 * Decode a Base64 encoded String to an OutputStream.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param string The data to decode.
	 * @param enc Character encoding to use when converting to and from bytes.
	 * @param out Stream to which to write decoded data.
	 * @throws UnsupportedEncodingException if the character encoding specified is not supported.
	 * @throws IOException if an IO error occurs.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static void decodeToStream(String string, String enc, OutputStream out) throws UnsupportedEncodingException, IOException {
		decode(new ByteArrayInputStream(string.getBytes(enc)), out);
	}

	/**
	 * Decode a Base64 encoded String.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 * The String is converted from bytes according to the platform's
	 * default character encoding.
	 *
	 * @param string The data to decode.
	 * @return decoded data.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static byte[] decodeToBytes(String string){
		return decode(string.getBytes());
	}

	/**
	 * Decode a Base64 encoded String.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param string The data to decode.
	 * @param enc Character encoding to use when converting from bytes.
	 * @throws UnsupportedEncodingException if the character encoding specified is not supported.
	 * @return decoded data.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static byte[] decodeToBytes(String string, String enc) throws UnsupportedEncodingException {
		return decode(string.getBytes(enc));
	}

	/**
	 * Decode Base64 encoded bytes.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 * The String is converted to bytes according to the platform's
	 * default character encoding.
	 *
	 * @param bytes The data to decode.
	 * @return A decoded String.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static String decodeToString(byte[] bytes){
		return new String(decode(bytes));
	}

	/**
	 * Decode Base64 encoded bytes.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param bytes The data to decode.
	 * @param enc Character encoding to use when converting to and from bytes.
	 * @throws UnsupportedEncodingException if the character encoding specified is not supported.
	 * @return A decoded String.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static String decodeToString(byte[] bytes, String enc) throws UnsupportedEncodingException {
		return new String(decode(bytes), enc);
	}

	/**
	 * Decode Base64 encoded bytes.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param bytes The data to decode.
	 * @return Decoded bytes.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static byte[] decodeToBytes(byte[] bytes){
		return decode(bytes);
	}

	/**
	 * Decode Base64 encoded bytes.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param bytes The data to decode.
	 * @return Decoded bytes.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static byte[] decode(byte[] bytes){
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		// calculate the length of the resulting output.
		// in general it will be at most 3/4 the size of the input
		// but the input length must be divisible by four.
		// If it isn't the next largest size that is divisible
		// by four is used.
		int mod;
		int length = bytes.length;
		if ((mod = length % 4) != 0){
			length += 4 - mod;
		}
		length = length * 3 / 4;
		ByteArrayOutputStream out = new ByteArrayOutputStream(length);
		try {
			decode(in, out, false);
		} catch (IOException x){
			// This can't happen.
			// The input and output streams were constructed
			// on memory structures that don't actually use IO.
			 throw new RuntimeException(x);
		}
		return out.toByteArray();
	}

	/**
	 * Decode Base64 encoded bytes to the an OutputStream.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param bytes The data to decode.
	 * @param out Stream to which to write decoded data.
	 * @throws IOException if an IO error occurs.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void decode(byte[] bytes, OutputStream out) throws IOException {
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		decode(in, out, false);
	}

	/**
	 * Decode Base64 encoded bytes to the an OutputStream.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param bytes The data to decode.
	 * @param out Stream to which to write decoded data.
	 * @throws IOException if an IO error occurs.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static void decodeToStream(byte[] bytes, OutputStream out) throws IOException {
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		decode(in, out, false);
	}

	/**
	 * Decode Base64 encoded data from one file to the other.
	 * Characters in the Base64 alphabet, white space and equals sign are
	 * expected to be in urlencoded data.  The presence of other characters
	 * could be a sign that the data is corrupted.
	 *
	 * @param fIn File to be decoded (will be overwritten).
	 * @throws IOException if an IO error occurs.
	 * @throws Base64DecodingException if unexpected data is encountered.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void decode(File fIn) throws IOException {
		decode(fIn, fIn, true);
	}

	/**
	 * Decode Base64 encoded data from one file to the other.
	 * Characters in the Base64 alphabet, white space and equals sign are
	 * expected to be in urlencoded data.  The presence of other characters
	 * could be a sign that the data is corrupted.
	 *
	 * @param fIn File to be decoded (will be overwritten).
	 * @param throwExceptions Whether to throw exceptions when unexpected data is encountered.
	 * @throws IOException if an IO error occurs.
	 * @throws Base64DecodingException if unexpected data is encountered when throwExceptions is specified.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void decode(File fIn, boolean throwExceptions) throws IOException {
		decode(fIn, fIn, throwExceptions);
	}

	/**
	 * Decode Base64 encoded data from one file to the other.
	 * Characters in the Base64 alphabet, white space and equals sign are
	 * expected to be in urlencoded data.  The presence of other characters
	 * could be a sign that the data is corrupted.
	 *
	 * @param fIn File to be decoded.
	 * @param fOut File to which the results should be written (may be the same as fIn).
	 * @throws IOException if an IO error occurs.
	 * @throws Base64DecodingException if unexpected data is encountered.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void decode(File fIn, File fOut) throws IOException {
		decode(fIn, fOut, true);
	}

	/**
	 * Decode Base64 encoded data from one file to the other.
	 * Characters in the Base64 alphabet, white space and equals sign are
	 * expected to be in urlencoded data.  The presence of other characters
	 * could be a sign that the data is corrupted.
	 *
	 * @param fIn File to be decoded.
	 * @param fOut File to which the results should be written (may be the same as fIn).
	 * @param throwExceptions Whether to throw exceptions when unexpected data is encountered.
	 * @throws IOException if an IO error occurs.
	 * @throws Base64DecodingException if unexpected data is encountered when throwExceptions is specified.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void decode(File fIn, File fOut, boolean throwExceptions) throws IOException {
		File temp = null;
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(fIn));
			temp = File.createTempFile("Base64", null, null);
			out = new BufferedOutputStream(new FileOutputStream(temp));
			decode(in, out, throwExceptions);
			in.close();
			in = null;
			out.flush();
			out.close();
			out = null;
			FileHelper.move(temp, fOut, true);
		} finally {
			if (in != null){
				try {
					in.close();
				} catch (IOException ignore){
					 if (throwExceptions) throw ignore;
				}
				in = null;
			}
			if (out != null){
				try {
					out.flush();
					out.close();
				} catch (IOException ignore){
					 if (throwExceptions) throw ignore;
				}
				out = null;
			}
		}
	}

	/**
	 * Reads the next (decoded) Base64 character from the input stream.
	 * Non Base64 characters are skipped.
	 *
	 * @param in Stream from which bytes are read.
	 * @param throwExceptions Throw an exception if an unexpected character is encountered.
	 * @return the next Base64 character from the stream or -1 if there are no more Base64 characters on the stream.
	 * @throws IOException if an IO Error occurs.
	 * @throws Base64DecodingException if unexpected data is encountered when throwExceptions is specified.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	private static final int readBase64(InputStream in, boolean throwExceptions) throws IOException {
		int read;
		int numPadding = 0;
		do {
			read = in.read();
			if (read == END_OF_INPUT) return END_OF_INPUT;
			read = reverseBase64Chars[(byte)read];
			if (throwExceptions && (read == NON_BASE_64 || (numPadding > 0 && read > NON_BASE_64))){
				throw new Base64DecodingException (
					MessageFormat.format(
						labels.getString("unexpectedchar"),
						(Object[])new String[] {
							"'" + (char)read + "' (0x" + Integer.toHexString(read) + ")"
						}
					),
					(char)read
				);
			}
			if (read == NON_BASE_64_PADDING){
				numPadding++;
			}
		} while (read <= NON_BASE_64);
		return read;
	}

	/**
	 * Decode Base64 encoded data from the InputStream to a byte array.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param in Stream from which to read data that needs to be decoded.
	 * @return decoded data.
	 * @throws IOException if an IO error occurs.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static byte[] decodeToBytes(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		decode(in, out, false);
		return out.toByteArray();
	}

	/**
	 * Decode Base64 encoded data from the InputStream to a String.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 * Bytes are converted to characters in the output String according to the platform's
	 * default character encoding.
	 *
	 * @param in Stream from which to read data that needs to be decoded.
	 * @return decoded data.
	 * @throws IOException if an IO error occurs.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static String decodeToString(InputStream in) throws IOException {
		return new String(decodeToBytes(in));
	}

	/**
	 * Decode Base64 encoded data from the InputStream to a String.
	 * Characters that are not part of the Base64 alphabet are ignored
	 * in the input.
	 *
	 * @param in Stream from which to read data that needs to be decoded.
	 * @param enc Character encoding to use when converting bytes to characters.
	 * @return decoded data.
	 * @throws IOException if an IO error occurs.Throws:
	 * @throws UnsupportedEncodingException if the character encoding specified is not supported.
	 *
	 * @since ostermillerutils 1.02.16
	 */
	public static String decodeToString(InputStream in, String enc) throws IOException {
		return new String(decodeToBytes(in), enc);
	}

	/**
	 * Decode Base64 encoded data from the InputStream to the OutputStream.
	 * Characters in the Base64 alphabet, white space and equals sign are
	 * expected to be in urlencoded data.  The presence of other characters
	 * could be a sign that the data is corrupted.
	 *
	 * @param in Stream from which to read data that needs to be decoded.
	 * @param out Stream to which to write decoded data.
	 * @throws IOException if an IO error occurs.
	 * @throws Base64DecodingException if unexpected data is encountered.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void decode(InputStream in, OutputStream out) throws IOException {
		decode(in, out, true);
	}

	/**
	 * Decode Base64 encoded data from the InputStream to the OutputStream.
	 * Characters in the Base64 alphabet, white space and equals sign are
	 * expected to be in urlencoded data.  The presence of other characters
	 * could be a sign that the data is corrupted.
	 *
	 * @param in Stream from which to read data that needs to be decoded.
	 * @param out Stream to which to write decoded data.
	 * @param throwExceptions Whether to throw exceptions when unexpected data is encountered.
	 * @throws IOException if an IO error occurs.
	 * @throws Base64DecodingException if unexpected data is encountered when throwExceptions is specified.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static void decode(InputStream in, OutputStream out, boolean throwExceptions) throws IOException {
		// Base64 decoding converts four bytes of input to three bytes of output
		int[] inBuffer = new int[4];

		// read bytes unmapping them from their ASCII encoding in the process
		// we must read at least two bytes to be able to output anything
		boolean done = false;
		while (!done && (inBuffer[0] = readBase64(in, throwExceptions)) != END_OF_INPUT
			&& (inBuffer[1] = readBase64(in, throwExceptions)) != END_OF_INPUT){
			// Fill the buffer
			inBuffer[2] = readBase64(in, throwExceptions);
			inBuffer[3] = readBase64(in, throwExceptions);

			// Calculate the output
			// The first two bytes of our in buffer will always be valid
			// but we must check to make sure the other two bytes
			// are not END_OF_INPUT before using them.
			// The basic idea is that the four bytes will get reconstituted
			// into three bytes along these lines:
			// [xxAAAAAA] [xxBBBBBB] [xxCCCCCC] [xxDDDDDD]
			//      [AAAAAABB] [BBBBCCCC] [CCDDDDDD]
			// bytes are considered to be zero when absent.

			// six A and two B
			out.write(inBuffer[0] << 2 | inBuffer[1] >> 4);
			if (inBuffer[2] != END_OF_INPUT){
				// four B and four C
				out.write(inBuffer[1] << 4 | inBuffer[2] >> 2);
				if (inBuffer[3] != END_OF_INPUT){
					// two C and six D
					out.write(inBuffer[2] << 6 | inBuffer[3]);
				} else {
					done = true;
				}
			} else {
				done = true;
			}
		}
		out.flush();
	}

	/**
	 * Determines if the byte array is in base64 format.
	 * <p>
	 * Data will be considered to be in base64 format if it contains
	 * only base64 characters and whitespace with equals sign padding
	 * on the end so that the number of base64 characters is divisible
	 * by four.
	 * <p>
	 * It is possible for data to be in base64 format but for it to not
	 * meet these stringent requirements.  It is also possible for data
	 * to meet these requirements even though decoding it would not make
	 * any sense.  This method should be used as a guide but it is not
	 * authoritative because of the possibility of these false positives
	 * and false negatives.
	 * <p>
	 * Additionally, extra data such as headers or footers may throw
	 * this method off the scent and cause it to return false.
	 *
	 * @param bytes data that could be in base64 format.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static boolean isBase64(byte[] bytes){
		try {
			return isBase64(new ByteArrayInputStream(bytes));
		} catch (IOException x){
			// This can't happen.
			// The input and output streams were constructed
			// on memory structures that don't actually use IO.
			return false;
		}
	}

	/**
	 * Determines if the String is in base64 format.
	 * The String is converted to and from bytes according to the platform's
	 * default character encoding.
	 * <p>
	 * Data will be considered to be in base64 format if it contains
	 * only base64 characters and whitespace with equals sign padding
	 * on the end so that the number of base64 characters is divisible
	 * by four.
	 * <p>
	 * It is possible for data to be in base64 format but for it to not
	 * meet these stringent requirements.  It is also possible for data
	 * to meet these requirements even though decoding it would not make
	 * any sense.  This method should be used as a guide but it is not
	 * authoritative because of the possibility of these false positives
	 * and false negatives.
	 * <p>
	 * Additionally, extra data such as headers or footers may throw
	 * this method off the scent and cause it to return false.
	 *
	 * @param string String that may be in base64 format.
	 * @return Best guess as to whether the data is in base64 format.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static boolean isBase64(String string){
		return isBase64(string.getBytes());
	}

	/**
	 * Determines if the String is in base64 format.
	 * <p>
	 * Data will be considered to be in base64 format if it contains
	 * only base64 characters and whitespace with equals sign padding
	 * on the end so that the number of base64 characters is divisible
	 * by four.
	 * <p>
	 * It is possible for data to be in base64 format but for it to not
	 * meet these stringent requirements.  It is also possible for data
	 * to meet these requirements even though decoding it would not make
	 * any sense.  This method should be used as a guide but it is not
	 * authoritative because of the possibility of these false positives
	 * and false negatives.
	 * <p>
	 * Additionally, extra data such as headers or footers may throw
	 * this method off the scent and cause it to return false.
	 *
	 * @param string String that may be in base64 format.
	 * @param enc Character encoding to use when converting to bytes.
	 * @return Best guess as to whether the data is in base64 format.
	 * @throws UnsupportedEncodingException if the character encoding specified is not supported.
	 */
	public static boolean isBase64(String string, String enc) throws UnsupportedEncodingException {
		return isBase64(string.getBytes(enc));
	}

	/**
	 * Determines if the File is in base64 format.
	 * <p>
	 * Data will be considered to be in base64 format if it contains
	 * only base64 characters and whitespace with equals sign padding
	 * on the end so that the number of base64 characters is divisible
	 * by four.
	 * <p>
	 * It is possible for data to be in base64 format but for it to not
	 * meet these stringent requirements.  It is also possible for data
	 * to meet these requirements even though decoding it would not make
	 * any sense.  This method should be used as a guide but it is not
	 * authoritative because of the possibility of these false positives
	 * and false negatives.
	 * <p>
	 * Additionally, extra data such as headers or footers may throw
	 * this method off the scent and cause it to return false.
	 *
	 * @param fIn File that may be in base64 format.
	 * @return Best guess as to whether the data is in base64 format.
	 * @throws IOException if an IO error occurs.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static boolean isBase64(File fIn) throws IOException {
		return isBase64(new BufferedInputStream(new FileInputStream(fIn)));
	}

	/**
	 * Reads data from the stream and determines if it is
	 * in base64 format.
	 * <p>
	 * Data will be considered to be in base64 format if it contains
	 * only base64 characters and whitespace with equals sign padding
	 * on the end so that the number of base64 characters is divisible
	 * by four.
	 * <p>
	 * It is possible for data to be in base64 format but for it to not
	 * meet these stringent requirements.  It is also possible for data
	 * to meet these requirements even though decoding it would not make
	 * any sense.  This method should be used as a guide but it is not
	 * authoritative because of the possibility of these false positives
	 * and false negatives.
	 * <p>
	 * Additionally, extra data such as headers or footers may throw
	 * this method off the scent and cause it to return false.
	 *
	 * @param in Stream from which to read data to be tested.
	 * @return Best guess as to whether the data is in base64 format.
	 * @throws IOException if an IO error occurs.
	 *
	 * @since ostermillerutils 1.00.00
	 */
	public static boolean isBase64(InputStream in) throws IOException {
		long numBase64Chars = 0;
		int numPadding = 0;
		int read;

		while ((read = in.read()) != -1){
			read = reverseBase64Chars[read];
			if (read == NON_BASE_64){
				return false;
			} else if (read == NON_BASE_64_WHITESPACE){
			} else if (read == NON_BASE_64_PADDING){
				numPadding++;
				numBase64Chars++;
			} else if (numPadding > 0){
				return false;
			} else {
				numBase64Chars++;
			}
		}
		if (numBase64Chars == 0) return false;
		if (numBase64Chars % 4 != 0) return false;
		return true;
	}
}

4.MD5:

MD5是一个安全的散列算法,有两个特点:
1、输入两个不同的明文(一段原始的数字信息)不会得到相同的输出值
2、根据输出值,不能得到原始的明文,即过程不可逆
所以要解密MD5没有现成的算法,只能用穷举法,把可能出现的明文,用MD5算法散列之后,把得到的散列值和原始的数据形成一个一对一的映射表,然后在所谓的解密的时候,都是通过这个映射表来查找其所对应的原始明文。
而绝对没有一种算法,可以通过输出加密后的散列值算出原始明文。
http://zhidao.baidu.com/link?url=8GALGyzvERNGndKHHz-Ds54funzwR6PrUJ2NdXS55hNePcgRJEYc2Puh7o9-3x18F85aahGw0x5Z7NhjDUZJHq


package com.gootrip.util;

// Md5.java
// $Id: Md5.java,v 1.4 1999/12/06 13:13:58 ylafon Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html
// http://www.jq-school.com
// 
//		Add model hmac_Md5 ( String text , String key ) ;
//package md5java ;
import java.io.* ;

public class Md5 {
    private static final int BUFFER_SIZE = 1024 ;

    private static final int S11 = 7 ;
    private static final int S12 = 12 ;
    private static final int S13 = 17 ;
    private static final int S14 = 22 ;
    private static final int S21 = 5 ;
    private static final int S22 = 9 ;
    private static final int S23 = 14 ;
    private static final int S24 = 20 ;
    private static final int S31 = 4 ;
    private static final int S32 = 11 ;
    private static final int S33 = 16 ;
    private static final int S34 = 23 ;
    private static final int S41 = 6 ;
    private static final int S42 = 10 ;
    private static final int S43 = 15 ;
    private static final int S44 = 21 ;

    private static byte padding[] = {
        (byte) 0x80, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
        (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
        (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
        (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
        (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
        (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
        (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
        (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
        (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
        (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
        (byte) 0, (byte) 0, (byte) 0, (byte) 0
    } ;


    private InputStream in       = null ;
    private boolean     stringp  = false ;
    private int         state[]  = null ;
    private long        count    = 0 ;
    private byte        buffer[] = null ;
    private byte        digest[] = null ;

    public static String stringify (byte buf[]) {
        StringBuffer sb = new StringBuffer(2*buf.length) ;
        for (int i = 0 ; i < buf.length; i++) {
            int h = (buf[i] & 0xf0) >> 4 ;
            int l = (buf[i] & 0x0f) ;
            sb.append (new Character((char)((h>9) ? 'a'+h-10 : '0'+h))) ;
            sb.append (new Character((char)((l>9) ? 'a'+l-10 : '0'+l))) ;
        }
        return sb.toString() ;
    }

    private final int F(int x, int y, int z) {
        return ((x & y) | ((~x) & z)) ;
    }

    private final int G(int x, int y, int z) {
        return ((x & z) | (y & (~z))) ;
    }

    private final int H(int x, int y, int z) {
        return (x ^ y ^ z) ;
    }

    private final int I(int x, int y, int z) {
        return (y ^ (x | (~z))) ;
    }

    private final int  rotate_left(int x, int n) {
        return ((x << n) | (x >>> (32-n))) ;
    }

    private final int FF(int a,int b,int c,int d,int x,int s,int ac) {
        a += (F(b, c, d) + x + ac) ;
        a = rotate_left(a, s) ;
        a += b ;
        return a ;
    }

    private final int GG(int a,int b,int c,int d,int x,int s,int ac) {
        a += (G(b, c, d) + x + ac) ;
        a = rotate_left(a, s) ;
        a += b ;
        return a ;
    }

    private final int HH(int a,int b,int c,int d,int x,int s,int ac) {
        a += (H(b, c, d) + x + ac) ;
        a = rotate_left(a, s) ;
        a += b ;
        return a ;
    }

    private final int II(int a,int b,int c,int d,int x,int s,int ac) {
        a += (I(b, c, d) + x + ac) ;
        a = rotate_left(a, s) ;
        a += b ;
        return a;
    }

    private final void decode (int output[], byte input[], int off, int len) {
        int i = 0 ;
        int j = 0 ;
        for ( ; j < len; i++, j += 4) {
            output[i] = (((int) (input[off+j]&0xff))
                         | (((int) (input[off+j+1] & 0xff)) << 8)
                         | (((int) (input[off+j+2] & 0xff)) << 16)
                         | (((int) (input[off+j+3] & 0xff)) << 24)) ;
        }
    }

    private final void transform (byte block[], int offset) {
        int a   = state[0] ;
        int b   = state[1] ;
        int c   = state[2] ;
        int d   = state[3] ;
        int x[] = new int[16] ;

        decode (x, block, offset, 64);
        /* Round 1 */
        a = FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
        d = FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
        c = FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
        b = FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
        a = FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
        d = FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
        c = FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
        b = FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
        a = FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
        d = FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
        c = FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
        b = FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
        a = FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
        d = FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
        c = FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
        b = FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
        /* Round 2 */
        a = GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
        d = GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
        c = GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
        b = GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
        a = GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
        d = GG (d, a, b, c, x[10], S22,  0x2441453); /* 22 */
        c = GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
        b = GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
        a = GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
        d = GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
        c = GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
        b = GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
        a = GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
        d = GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
        c = GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
        b = GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */

        /* Round 3 */
        a = HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
        d = HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
        c = HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
        b = HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
        a = HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
        d = HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
        c = HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
        b = HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
        a = HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
        d = HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
        c = HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
        b = HH (b, c, d, a, x[ 6], S34,  0x4881d05); /* 44 */
        a = HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
        d = HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
        c = HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
        b = HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */

        /* Round 4 */
        a = II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
        d = II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
        c = II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
        b = II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
        a = II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
        d = II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
        c = II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
        b = II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
        a = II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
        d = II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
        c = II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
        b = II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
        a = II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
        d = II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
        c = II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
        b = II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */

        state[0] += a;
        state[1] += b;
        state[2] += c;
        state[3] += d;
    }

    private final void update (byte input[], int len) {
        int index = ((int) (count >> 3)) & 0x3f ;
        count += (len << 3) ;
        int partLen = 64 - index ;
        int i = 0 ;
        if ( len >= partLen ) {
            System.arraycopy (input, 0, buffer, index, partLen) ;
            transform (buffer, 0) ;
            for (i = partLen ; i + 63 < len ; i+= 64)
                transform (input, i) ;
            index = 0 ;
        } else {
            i = 0 ;
        }
        System.arraycopy (input, i, buffer, index, len - i) ;
    }

    private byte[] end () {
        byte bits[] = new byte[8] ;
        for (int i = 0 ; i < 8 ; i++)
            bits[i] = (byte) ((count>>>(i*8)) & 0xff) ;
        int index  = ((int) (count >> 3)) & 0x3f ;
        int padlen = (index < 56) ? (56 - index) : (120 - index) ;
        update (padding, padlen) ;
        update (bits, 8) ;
        return encode(state, 16) ;
    }

    // Encode the content.state array into 16 bytes array
    private byte[] encode (int input[], int len) {
        byte output[] = new byte[len] ;
        int i = 0 ;
        int j = 0 ;
        for ( ; j < len ; i++, j+= 4) {
            output[j]   = (byte) ((input[i]      ) & 0xff) ;
            output[j+1] = (byte) ((input[i] >> 8 ) & 0xff) ;
            output[j+2] = (byte) ((input[i] >> 16) & 0xff) ;
            output[j+3] = (byte) ((input[i] >> 24) & 0xff) ;
        }
        return output ;
    }

    /**
     * Get the digest for our input stream.
     * This method constructs the input stream digest, and return it, as a
     * a String, following the MD5 (rfc1321) algorithm,
     * @return An instance of String, giving the message digest.
     * @exception IOException Thrown if the digestifier was unable to read the
     *    input stream.
     */

    public byte[] getDigest ()
        throws IOException
    {
        byte buffer[] = new byte[BUFFER_SIZE] ;
        int  got      = -1 ;

        if ( digest != null )
            return digest ;
        while ((got = in.read(buffer)) > 0 )
            update (buffer, got) ;
        this.digest = end () ;
        return digest ;
    }

    /**
     * Get the digest, for this string digestifier.
     * This method doesn't throw any IOException, since it knows that the
     * underlying stream ws built from a String.
     */

    public byte[] processString () {
        if ( ! stringp )
            throw new RuntimeException (this.getClass().getName()
                                        + "[processString]"
                                        + " not a string.") ;
        try {
            return getDigest() ;
        } catch (IOException ex) {
        }
        throw new RuntimeException (this.getClass().getName()
                                    + "[processString]"
                                    + ": implementation error.") ;
    }

    /**
     * Get the digest, as a proper string.
     */

    public String getStringDigest() {
        if ( digest == null )
            throw new RuntimeException (this.getClass().getName()
                                        + "[getStringDigest]"
                                        + ": called before processing.") ;
        return stringify (digest) ;
    }


    /**
     * Construct a digestifier for the given string.
     * @param input The string to be digestified.
     * @param encoding the encoding name used (such as UTF8)
     */

    public Md5 (String input, String enc) {
         byte bytes [] = null;
        try {
            bytes = input.getBytes (enc);
        } catch(UnsupportedEncodingException e){
            throw new RuntimeException("no "+enc+" encoding!!!");
        }
        this.stringp = true ;
        this.in      = new ByteArrayInputStream (bytes) ;
        this.state   = new int[4] ;
        this.buffer  = new byte[64] ;
        this.count   = 0 ;
        state[0] = 0x67452301;
        state[1] = 0xefcdab89;
        state[2] = 0x98badcfe;
        state[3] = 0x10325476;
    }

    /**
     * Construct a digestifier for the given string.
     * @param input The string to be digestified.
     */

    public Md5 (String input) {
        this(input, "UTF8");
    }

    /**
     * Construct a digestifier for the given input stream.
     * @param in The input stream to be digestified.
     */

    public Md5 (InputStream in) {
        this.stringp = false ;
        this.in      = in ;
        this.state   = new int[4] ;
        this.buffer  = new byte[64] ;
        this.count   = 0 ;
        state[0] = 0x67452301;
        state[1] = 0xefcdab89;
        state[2] = 0x98badcfe;
        state[3] = 0x10325476;
    }

        public void hmac_Md5 ( String text , String key )
        throws IOException {
                //byte disgest[] = new byte[16] ;
                //byte output[] = new byte[32] ;
                //output[33] = ( byte ) '\0' ;
                byte k_ipad[] = new byte[64] ;
                byte k_opad[] = new byte[64] ;
                //byte tk[] = new byte[16] ;
                byte key1 [] ;
                int i ;
                int text_len = text.getBytes().length ;
                int key_len = key.getBytes().length ;
                key1 = key.getBytes() ;

                if ( key_len > 64 ) {
                        key1 = new Md5( key ).getDigest() ;
                        key_len = 16 ;
                }

                for ( i = 0 ; i < 64 ; i++ )
                        k_ipad[i] = ( byte ) 0 ;
                for ( i = 0 ; i < 64 ; i++ )
                        k_opad[i] = ( byte ) 0 ;

                for ( i = 0 ; i < key_len ; i++ ) {
                        k_ipad[i] = ( byte ) key1[i] ;
                        k_opad[i] = ( byte ) key1[i] ;
                }

                for ( i = 0 ; i < 64 ; i++ ) {
                        k_ipad[i] ^= 0x36 ;
                        k_opad[i] ^= 0x5c ;
                }

                Md5 md5 = new Md5( "" ) ;
                md5.update( k_ipad , 64 ) ;
                md5.update( text.getBytes() , text_len ) ;
                digest = md5.getDigest() ;

                Md5 md51 = new Md5( "" ) ;
                md51.update( k_opad , 64 ) ;
                md51.update( digest , 16 ) ;
                digest = md51.getDigest() ;
        }



}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值