为情书加密的BASE64的java类

来源:互联网 发布:cnn 文本相似 java 编辑:程序博客网 时间:2024/04/30 06:53

最近自己写了个用BASE64编码“加密”的小java类,觉得有点意思,发出来一下,希望大家不要见笑

 

/*author: livahu
 *
 *用于编码BASE64t和解码BASE64
 *
 
*/

import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.FileNotFoundException;
import java.util.Scanner;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class BASE64 
{
    
//将s进行BASE64编码
    public static String getBASE64EncoderStr(String s) throws UnsupportedEncodingException
    
{
        
if (null == s)
            
return null;
        
else
            
return new BASE64Encoder().encode(s.getBytes("GB2312"));
    }

    
//将s进行BASE64解码
    public static byte[] getBASE64DecoderBt(String s) throws IOException
    
{
        
if (null == s)
            
return null;
        
else
        
{
            BASE64Decoder decoder 
= new BASE64Decoder();
            
return decoder.decodeBuffer(s);
        }


    }

    
//将指定文件用BASE64编码
    public static void changeToBASE64(String filePath) throws IOException
    
{
        Scanner sc 
= new Scanner(new FileInputStream(filePath)).useDelimiter(" ");
        PrintWriter pw 
= new PrintWriter(filePath + "_BASE64_");
        
while (sc.hasNext())
        
{
            pw.println(getBASE64EncoderStr(sc.next()));
        }

        sc.close();
        pw.close();
    }

    
//将指定文件从BASE64解码
    public static void recoverFromBASE64(String filePath) throws IOException, FileNotFoundException
    
{
        Scanner sc 
= new Scanner(new FileInputStream(filePath)).useDelimiter(" ");
        PrintWriter out 
= new PrintWriter(filePath.substring(0, filePath.indexOf("_BASE64_")));
        
while (sc.hasNext())
        
{
            out.println(
new String(getBASE64DecoderBt(sc.next()), "GB2312"));
        }

        sc.close();
        out.close();
    }

    
//main方法
    public static void main(String[] args)
    
{
        
try
        
{
            
if (args[0].indexOf("_BASE64_"> 0)
            
{
                recoverFromBASE64(args[
0]);
            }

            
else
            
{
                changeToBASE64(args[
0]);
            }

        }

        
catch (IOException e)
        
{
            System.out.println(
"Catch some IOException!");
        }

    }

}


 

下面是批处理文件

 

rem   author:livahu
@echo off
set CLASSPATH=你放BASE64.java的目录;%CLASSPATH%
java BASE64 
%1
del %1

 

只要把任意文件往BASE64.bat一拖就好了,呵呵。

原创粉丝点击