Base64 decryption, encrypted file or string [I have added a string for encryption and decryption]

Source: Internet
Author: User

/**
* Encrypt the string with a 64-bit encryption algorithm
* Title: sales automation software
* Description: enables the salesperson to manage the sales process through a single software. Information can be shared with each other at the same time.
* Compatible with earlier ACT and OUTLOOK software.
* Integration with OFFICE software.
* Copyright: Copyright (c) 2001
* Company: TCL enterprise software Co., Ltd.
* @ Author TONY Zheng
* @ Date 17 march2000
* @ Version 1.0
*/

/// // License & copyright header ////////////// ///////////
////
// Base64-encode/decode data using the Base64 encoding scheme //
////
// Copyright (c) 1998 by Kevin Kelley //
////
// This library is free software; you can redistribute it and/or //
// Modify it under the terms of the GNU Lesser General Public //
// License as published by the Free Software Foundation; either //
// Version 2.1 of the License, or (at your option) any later version .//
////
// This library is distributed in the hope that it will be useful ,//
// But without any warranty; without even the implied warranty //
// MERCHANTABILITY or fitness for a special PURPOSE. See //
// GNU Lesser General Public License for more details .//
////
// You shoshould have written ed a copy of the GNU Lesser General Public //
// License along with this library; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place-Suite 330, Boston, MA //
// 02111-1307, USA, or contact the author ://
////
// Kevin Kelley <kelley@ruralnet.net>-30718 Rd. 28, La Junta, CO ,//
// 81050 USA .//
////
/// // End license & copyright header /////////////// ////////

Import java. io. *; // needed only for main () method.

/**
* Provides encoding of raw bytes to base64-encoded characters, and
* Decoding of base64 characters to raw bytes.
* Used for encryption algorithms, 64-bit encryption software
* @ Author Kevin Kelley (kelley@ruralnet.net)
* @ Version 1.3
* @ Date 06 August 1998
* @ Modified 14 February 2000
* @ Modified 22 September 2000
*/

Public class Base64 {

/**
* Returns an array of base64-encoded characters to represent
* Passed data array.
*
* @ Param data the array of bytes to encode
* @ Return base64-coded character array.
*/
Static public char [] encode (byte [] data)
{
Char [] out = new char [(data. length + 2)/3) * 4];

//
// 3 bytes encode to 4 chars. Output is always an even
// Multiple of 4 characters.
//
For (int I = 0, index = 0; I <data. length; I + = 3, index + = 4 ){
Boolean quad = false;
Boolean trip = false;

Int val = (0xFF & (int) data [I]);
Val <= 8;
If (I + 1) <data. length ){
Val | = (0xFF & (int) data [I + 1]);
Trip = true;
}
Val <= 8;
If (I + 2) <data. length ){
Val | = (0xFF & (int) data [I + 2]);
Quad = true;
}
Out [index + 3] = alphabet [(quad? (Val & 0x3F): 64)];
Val >>=6;
Out [index + 2] = alphabet [(trip? (Val & 0x3F): 64)];
Val >>=6;
Out [index + 1] = alphabet [val & 0x3F];
Val >>=6;
Out [index + 0] = alphabet [val & 0x3F];
}
Return out;
}

/**
* Decodes a BASE-64 encoded stream to recover the original
* Data. White space before and after will be trimmed away,
* But no other manipulation of the input will be saved med.
*
* As of version 1.2 this method will properly handle input
* Containing junk characters (newlines and the like) rather
* Than throwing an error. It does this by pre-parsing
* Input and generating from that a count of VALID input
* Characters.
**/
Static public byte [] decode (char [] data)
{
// As our input cocould contain non-BASE64 data (newlines,
// Whitespace of any sort, whatever) we must first adjust
// Our count of USABLE data so that...
// (A) we don't misallocate the output array, and
// (B) think that we miscalculated our data length
// Just because of extraneous throw-away junk

Int tempLen = data. length;
For (int ix = 0; ix <data. length; ix ++)
{
If (data [ix]> 255) | codes [data [ix] <0)
-- TempLen; // ignore non-valid chars and padding
}
// Calculate required length:
// -- 3 bytes for every 4 valid base64 chars
// -- Plus 2 bytes if there are 3 extra base64 chars,
// Or plus 1 byte if there are 2 extra.

Int len = (tempLen/4) * 3;
If (tempLen % 4) = 3) len + = 2;
If (tempLen % 4) = 2) len + = 1;

Byte [] out = new byte [len];

 

Int shift = 0; // # of excess bits stored in accum
Int accum = 0; // excess bits
Int index = 0;

// We now go through the entire array (NOT using the 'templen' value)
For (int ix = 0; ix <data. length; ix ++)
{
Int value = (data [ix]> 255 )? -1: codes [data [ix];

If (value> = 0) // skip over non-code
{
Accum <= 6; // bits shift up by 6 each time thru
Shift + = 6; // loop, with new bits being put in
Accum | = value; // at the bottom.
If (shift> = 8) // whenever there are 8 or more shifted in,
{
Shift-= 8; // write them out (from the top, leaving any
Out [index ++] = // excess at the bottom for next iteration.
(Byte) (accum> shift) & 0xff );
}
}
// We will also have skipped processing a padding null byte ('=') here;
// These are used ONLY for padding to an even length and do not legally
// Occur as encoded data. for this reason we can ignore the fact that
// No index ++ operation occurs in that special case: the out [] array is
// Initialized to all-zero bytes to start with and that works to our
// Advantage in this combination.
}

// If there is STILL something wrong we just have to throw up now!
If (index! = Out. length)
{
Throw new Error ("Miscalculated data length (wrote" + index + "instead of" + out. length + ")");
}

Return out;
}

//
// Code characters for values 0 .. 63
//
Static private char [] alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 +/="
. ToCharArray ();

//
// Lookup table for converting base64 characters to value in range 0 .. 63
//
Static private byte [] codes = new byte [1, 256];
Static {
For (int I = 0; I <256; I ++) codes [I] =-1;
For (int I = 'a'; I <= 'Z'; I ++) codes [I] = (byte) (I-'A ');
For (int I = 'a'; I <= 'Z'; I ++) codes [I] = (byte) (26 + I-'A ');
For (int I = '0'; I <= '9'; I ++) codes [I] = (byte) (52 + I-'0 ');
Codes ['+'] = 62;
Codes ['/'] = 63;
}

Static public String encode (String data)
{
String temp;
If (null = data)
{
Temp = "";
}
Else
{
Byte [] bt = data. getBytes ();
Char [] btc = encode (bt );
Temp = String. valueOf (btc );
}
Return temp;
}

Static public String decode (String data)
{
String temp;
If (null = data)
{
Temp = "";
}
Else
{
Char [] cc = data. toCharArray ();
Byte [] bt = decode (cc );
Int I = 0;
String temp2 = "";
For (; I <bt. length; I ++)
{
Int s = bt [I];
Char ch = (char) s;
Temp2 + = ch;
}
Temp = temp2;
}
Return temp;
}
//////////////////////////////////////// ///////////
// Remainder (main method and helper functions) is
// For testing purposes only, feel free to clip it.
//////////////////////////////////////// ///////////

Public static void main (String [] args)
{
Boolean decode = false;

If (args. length = 0 ){
System. out. println ("usage: java Base64 [-d [ecode] filename ");
System. exit (0 );
}
For (int I = 0; I <args. length; I ++ ){
If ("-decode". inclusignorecase (args [I]) decode = true;
Else if ("-d". inclusignorecase (args [I]) decode = true;
}

String filename = args [args. length-1];
File file = new File (filename );
If (! File. exists ()){
System. out. println ("Error: file'" + filename + "'doesn' t exist! ");
System. exit (0 );
}

If (decode)
{
Char [] encoded = readChars (file );
Byte [] decoded = decode (encoded );
WriteBytes (file, decoded );
}
Else
{
Byte [] decoded = readBytes (file );
Char [] encoded = encode (decoded );
WriteChars (file, encoded );
}
}

Private static byte [] readBytes (File file)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
Try
{
InputStream FCM = new FileInputStream (file );
InputStream is = new BufferedInputStream (FCM );
Int count = 0;
Byte [] buf = new byte [1, 16384];
While (count = is. read (buf ))! =-1 ){
If (count> 0) baos. write (buf, 0, count );
}
Is. close ();
}
Catch (Exception e) {e. printStackTrace ();}

Return baos. toByteArray ();
}

Private static char [] readChars (File file)
{
CharArrayWriter caw = new CharArrayWriter ();
Try
{
Reader fr = new FileReader (file );
Reader in = new BufferedReader (fr );
Int count = 0;
Char [] buf = new char [16384];
While (count = in. read (buf ))! =-1 ){
If (count> 0) caw. write (buf, 0, count );
}
In. close ();
}
Catch (Exception e) {e. printStackTrace ();}

Return caw. toCharArray ();
}

Private static void writeBytes (File file, byte [] data ){
Try {
OutputStream fos = new FileOutputStream (file );
OutputStream OS = new BufferedOutputStream (fos );
OS. write (data );
OS. close ();
}
Catch (Exception e) {e. printStackTrace ();}
}

Private static void writeChars (File file, char [] data ){
Try {
Writer fos = new FileWriter (file );
Writer OS = new BufferedWriter (fos );
OS. write (data );
OS. close ();
}
Catch (Exception e) {e. printStackTrace ();}
}
//////////////////////////////////////// ///////////
// End of test code.
//////////////////////////////////////// ///////////

}

 

Usage:

 

File encryption: java Base64 file.txt

File decryption: java Base64-d file.txt

 

String encryption: Base64.encode (String enstr)

String decryption: Base64.decode (String destr)

 

Unsolved: If request. setCharacterEncoding ("GBK") is not added when decode is output to the page ");

 

The Chinese output is normal.

 

If it is added, the Chinese characters in the page of the program are normal, and the decrypted Chinese data is abnormal. Confusion .............

 

 

I would be grateful if the worm could tell me the solution.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.