`
jilong-liang
  • 浏览: 479122 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类

java的BASE64Encoder,BASE64Decoder加密与解密

    博客分类:
  • Java
阅读更多
package com.app.common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *@DEMO:napp
 *@Author:jilongliang
 *@Date:2013-7-25
 */
@SuppressWarnings("all")
public class EDncrypt {
	private static BASE64Encoder encoder = new  BASE64Encoder();// 加密
	private static BASE64Decoder decoder = new  BASE64Decoder();// 解密
	
	/**
	 * 加密文件
	 * 
	 * @param f
	 * @param path
	 */
	private static String encryptFile(File f, String path) {
		InputStream in = null;
		OutputStream out = null;
		String key = "";
		try {
			f = new File(path);
			in = new FileInputStream(f);
			out = new ByteArrayOutputStream();
			// System.out.println(f.getAbsolutePath());
			// System.out.println(f.length());
			encoder.encodeBuffer(in, out);
			key = out.toString();
			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return key;
	}
	/**
	 *解密
	 * 
	 * @param f
	 * @param path
	 */
	private static String decryptFile(File f, String path) {
		InputStream in = null;
		OutputStream out = null;
		String key = "";
		try {
			f = new File(path);
			in = new FileInputStream(f);
			out = new ByteArrayOutputStream();
			decoder.decodeBuffer(in, out);
			key = out.toString();
			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return key;
	}


	/**
	 * 加密
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encryptBASE64(String inputStr) {
		String value = "";
		try {
			byte[] key = inputStr.getBytes();
			value = encoder.encodeBuffer(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	/**
	 * 解密
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String decryptBASE64(String outputStr) {
		String value = "";
		try {
			byte[] key = decoder.decodeBuffer(outputStr);
			value = new String(key);
		} catch (Exception e) {
		}
		return value;
	}
}

 

0
6
分享到:
评论
2 楼 freezingsky 2013-08-14  
/*
 * %W% %E%
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.util.prefs;

/**
 * Static methods for translating Base64 encoded strings to byte arrays
 * and vice-versa.
 *
 * @author  Josh Bloch
 * @version %I%, %G%
 * @see     Preferences
 * @since   1.4
 */
class Base64 {
    /**
     * Translates the specified byte array into a Base64 string as per
     * Preferences.put(byte[]).
     */
    static String byteArrayToBase64(byte[] a) {
        return byteArrayToBase64(a, false);
    }

    /**
     * Translates the specified byte array into an "alternate representation"
     * Base64 string.  This non-standard variant uses an alphabet that does
     * not contain the uppercase alphabetic characters, which makes it
     * suitable for use in situations where case-folding occurs.
     */
    static String byteArrayToAltBase64(byte[] a) {
        return byteArrayToBase64(a, true);
    }

    private static String byteArrayToBase64(byte[] a, boolean alternate) {
        int aLen = a.length;
        int numFullGroups = aLen/3;
        int numBytesInPartialGroup = aLen - 3*numFullGroups;
        int resultLen = 4*((aLen + 2)/3);
        StringBuffer result = new StringBuffer(resultLen);
        char[] intToAlpha = (alternate ? intToAltBase64 : intToBase64);

        // Translate all full groups from byte array elements to Base64
        int inCursor = 0;
        for (int i=0; i<numFullGroups; i++) {
            int byte0 = a[inCursor++] & 0xff;
            int byte1 = a[inCursor++] & 0xff;
            int byte2 = a[inCursor++] & 0xff;
            result.append(intToAlpha[byte0 >> 2]);
            result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
            result.append(intToAlpha[(byte1 << 2)&0x3f | (byte2 >> 6)]);
            result.append(intToAlpha[byte2 & 0x3f]);
        }

        // Translate partial group if present
        if (numBytesInPartialGroup != 0) {
            int byte0 = a[inCursor++] & 0xff;
            result.append(intToAlpha[byte0 >> 2]);
            if (numBytesInPartialGroup == 1) {
                result.append(intToAlpha[(byte0 << 4) & 0x3f]);
                result.append("==");
            } else {
                // assert numBytesInPartialGroup == 2;
                int byte1 = a[inCursor++] & 0xff;
                result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
                result.append(intToAlpha[(byte1 << 2)&0x3f]);
                result.append('=');
            }
        }
        // assert inCursor == a.length;
        // assert result.length() == resultLen;
        return result.toString();
    }

    /**
     * This array is a lookup table that translates 6-bit positive integer
     * index values into their "Base64 Alphabet" equivalents as specified 
     * in Table 1 of RFC 2045.
     */
    private static final char intToBase64[] = {
        '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', '+', '/'
    };

    /**
     * This array is a lookup table that translates 6-bit positive integer
     * index values into their "Alternate Base64 Alphabet" equivalents.
     * This is NOT the real Base64 Alphabet as per in Table 1 of RFC 2045.
     * This alternate alphabet does not use the capital letters.  It is
     * designed for use in environments where "case folding" occurs.
     */
    private static final char intToAltBase64[] = {
        '!', '"', '#', '$', '%', '&', '\'', '(', ')', ',', '-', '.', ':',
        ';', '<', '>', '@', '[', ']', '^',  '`', '_', '{', '|', '}', '~',
        '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', '+', '?'
    };

    /**
     * Translates the specified Base64 string (as per Preferences.get(byte[]))
     * into a byte array.
     * 
     * @throw IllegalArgumentException if <tt>s</tt> is not a valid Base64
     *        string.
     */
    static byte[] base64ToByteArray(String s) {
        return base64ToByteArray(s, false);
    }

    /**
     * Translates the specified "alternate representation" Base64 string
     * into a byte array.
     * 
     * @throw IllegalArgumentException or ArrayOutOfBoundsException
     *        if <tt>s</tt> is not a valid alternate representation
     *        Base64 string.
     */
    static byte[] altBase64ToByteArray(String s) {
        return base64ToByteArray(s, true);
    }

    private static byte[] base64ToByteArray(String s, boolean alternate) {
        byte[] alphaToInt = (alternate ?  altBase64ToInt : base64ToInt);
        int sLen = s.length();
        int numGroups = sLen/4;
        if (4*numGroups != sLen)
            throw new IllegalArgumentException(
                "String length must be a multiple of four.");
        int missingBytesInLastGroup = 0;
        int numFullGroups = numGroups;
        if (sLen != 0) {
            if (s.charAt(sLen-1) == '=') {
                missingBytesInLastGroup++;
                numFullGroups--;
            }
            if (s.charAt(sLen-2) == '=')
                missingBytesInLastGroup++;
        }
        byte[] result = new byte[3*numGroups - missingBytesInLastGroup];

        // Translate all full groups from base64 to byte array elements
        int inCursor = 0, outCursor = 0;
        for (int i=0; i<numFullGroups; i++) {
            int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
            int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
            int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
            int ch3 = base64toInt(s.charAt(inCursor++), alphaToInt);
            result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
            result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
            result[outCursor++] = (byte) ((ch2 << 6) | ch3);
        }

        // Translate partial group, if present
        if (missingBytesInLastGroup != 0) {
            int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
            int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
            result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));

            if (missingBytesInLastGroup == 1) {
                int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
                result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
            }
        }
        // assert inCursor == s.length()-missingBytesInLastGroup;
        // assert outCursor == result.length;
        return result;
    }

    /**
     * Translates the specified character, which is assumed to be in the
     * "Base 64 Alphabet" into its equivalent 6-bit positive integer.
     *
     * @throw IllegalArgumentException or ArrayOutOfBoundsException if
     *        c is not in the Base64 Alphabet.
     */
    private static int base64toInt(char c, byte[] alphaToInt) {
        int result = alphaToInt[c];
        if (result < 0)
            throw new IllegalArgumentException("Illegal character " + c);
        return result;
    }

    /**
     * This array is a lookup table that translates unicode characters
     * drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045)
     * into their 6-bit positive integer equivalents.  Characters that
     * are not in the Base64 alphabet but fall within the bounds of the
     * array are translated to -1.
     */
    private static final byte base64ToInt[] = {
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
        55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
        5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
        24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
        35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
    };

    /**
     * This array is the analogue of base64ToInt, but for the nonstandard
     * variant that avoids the use of uppercase alphabetic characters.
     */
    private static final byte altBase64ToInt[] = {
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
        2, 3, 4, 5, 6, 7, 8, -1, 62, 9, 10, 11, -1 , 52, 53, 54, 55, 56, 57,
        58, 59, 60, 61, 12, 13, 14, -1, 15, 63, 16, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, 17, -1, 18, 19, 21, 20, 26, 27, 28, 29, 30, 31, 32, 33,
        34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
        51, 22, 23, 24, 25
    };
    
    public static void main(String args[]) {
        int numRuns  = Integer.parseInt(args[0]);
        int numBytes = Integer.parseInt(args[1]);
        java.util.Random rnd = new java.util.Random();
        for (int i=0; i<numRuns; i++) {
            for (int j=0; j<numBytes; j++) {
                byte[] arr = new byte[j];
                for (int k=0; k<j; k++)
                    arr[k] = (byte)rnd.nextInt();

                String s = byteArrayToBase64(arr);
                byte [] b = base64ToByteArray(s);
                if (!java.util.Arrays.equals(arr, b))
                    System.out.println("Dismal failure!");

                s = byteArrayToAltBase64(arr);
                b = altBase64ToByteArray(s);
                if (!java.util.Arrays.equals(arr, b))
                    System.out.println("Alternate dismal failure!");
            }
        }
    }
}
其实java包里不是有自带的吗。。。
1 楼 fangshun 2013-07-26  
挺好,就是catch里面是否应该加上流关闭代码。

相关推荐

    java 图片base64 加密解密

    总结来说,Java中的图片Base64加密解密涉及了二进制数据与ASCII字符串之间的转换,这对于在网络上传输或存储非文本数据(如图像)非常有用。虽然`sun.misc`包中的类已不再推荐,但理解其工作原理有助于更好地理解和...

    sun.misc.BASE64Decoder和sun.misc.BASE64Encoder不可用已解决

    冲浪后发现JDK中的lib\tools.jar和JRE中的lib\rt.jar已从Java SE 9中删除,也就是1.8版本后的jdk已经不再支持sun.misc.BASE64Decoder和sun.misc.BASE64Encoder。 这些JAR中可用的类和资源现在以文件中的内部格式存储...

    BASE64Encoder加密与解密

    在Java中,`sun.misc.BASE64Encoder`和`sun.misc.BASE64Decoder`类提供了对BASE64编码和解码的支持。然而,需要注意的是,这两个类自JDK 9起已被弃用,建议使用`java.util.Base64`包中的`Base64.getEncoder()`和`...

    BASE64Decoder包

    加密后字符串:String newKey=(new BASE64Encoder()).encodeBuffer(bt); 解密代码: 加密后的字符串:String newkey="*****"; byte[] bt = (new BASE64Decoder()).decodeBuffer(key); 解密后的字符串: String key=...

    BASE64加密解密

    【标签】:"java base64 Decoder Encoder 加密解密" 在Java中,BASE64的加密和解密操作主要依赖于`java.util.Base64`类,该类从Java 8开始引入,提供了完整的BASE64编码和解码功能。其中,`Encoder`接口用于进行...

    JavaBase64Decoder

    JavaBase64Decoder是Java中处理Base64编码和解码的一个重要工具,它与BASE64Encoder一起工作,提供了一种将字节数组与Base64字符串之间的转换方式。Base64是一种用于在网络上传输二进制数据的编码方式,它将任意的...

    用Java实现BASE64加密解密

    总之,Java提供了方便的`java.util.Base64`工具类来处理Base64编码和解码,使得在Java项目中实现Base64加密解密变得简单且高效。这个基础的加密解密机制虽然简单,但在很多场景下已经足够满足基本的数据保护需求。

    BASE64Decoder jar包

    总的来说,Base64Decoder是Java中用于处理Base64编码数据的重要工具,它简化了二进制数据与ASCII文本之间的转换过程,广泛应用于各种网络通信和数据存储场景。理解其工作原理并掌握如何使用Base64Decoder,对进行...

    base64转码解密成明文加密成Java密文

    本主题将深入探讨“Base64转码解密成明文”以及“Base64加密成Java密文”的过程,并介绍相关的Java实现。 首先,我们来看Base64解码。Base64编码的基本原理是将每3个字节的数据(24位)分成4组,每组6位,然后将这6...

    java实现SHA1、SHA、MD5、AES加密、AES解密、BASE64解密、BASE64加密,以及BASE64 jar和源码

    Java标准库提供`java.util.Base64`类,包括`Encoder`和`Decoder`接口,用于进行BASE64的编码和解码操作。 5. **Apache Commons Codec**: 这个库也提供了BASE64编码和解码功能,可能更易用且功能更丰富。例如,`org....

    java实现base64加密

    下面我们将详细探讨如何在Java中实现Base64加密和解密: 1. **Base64编码**: 使用`java.util.Base64.Encoder`接口的`encodeToString()`方法可以将字节数组编码为Base64字符串。例如: ```java byte[] bytes = ...

    RSA加密JAVA实现+sun.misc.BASE64Decoder.jar

    总的来说,这个压缩包提供的RSA加密解密Java实现,结合了Base64编码,提供了一种安全地传输和存储敏感信息的方法。在实际应用中,还需要考虑其他因素,如密钥的管理、安全性策略以及错误处理等。

    java使用base64加密

    在Java中,我们可以使用内置的`java.util.Base64`类来进行Base64的加密和解密操作。 Base64加密(编码)的过程是这样的:首先,输入的数据被分为每三个字节一组,因为每个字节有8位,三个字节共有24位。Base64将这...

    Base64批量加密工具

    1. **Base64Encoder和Base64Decoder**:这两个是`java.util.Base64`类库中的核心接口,分别用于编码和解码。使用`getEncoder()`和`getDecoder()`静态方法可以获取对应的实例。 2. **编码过程**:对于一个字节数组,...

    Base64.java加密解密类文件

    在Java中,`java.util.Base64`类提供了三种不同的编码器和解码器:`Encoder`、`Decoder`以及`Get`和`Set`方法。`Encoder`用于将字节数据编码为Base64字符串,而`Decoder`则负责将Base64字符串解码回原始字节数据。...

    基于java BASE64Decoder 算法实现数据库账号的加密解密的源码-EncryptAndDecryption.zip

    总的来说,基于Java的BASE64Decoder算法实现的数据库账号加密解密方案是一种有效的保护措施。通过结合BASE64编码和对称加密算法,可以为敏感数据提供一层额外的防护,降低数据泄露的风险。在实际开发中,还需要考虑...

    加密解密Base64的js封装代码

    本文将深入探讨Base64编码原理,JavaScript中的实现方式,以及如何封装一个Base64的加密解密工具。 Base64编码的基本原理是将每3个字节(24位)的数据拆分为4组,每组6位,然后将这6位二进制数据转换为其对应的...

    BASE64加密源码完整JAR包

    在Java中,我们可以使用内置的`java.util.Base64`类来实现BASE64的加密和解密操作。这个"BASE64加密源码完整JAR包"很可能包含了一个或者多个Java类,提供了方便的BASE64编码接口,便于开发者集成到他们的项目中。 ...

    java 把PDF转换成BASE64

    在IT行业中,编码和解码是常见的...总之,Java提供了便捷的工具来实现PDF与BASE64之间的转换,这对于在网络上传输或存储PDF文件非常有用。在实际项目中,根据具体需求,可能还需要结合其他库和方法来完善整个处理流程。

    Base64加密解密

    在Java编程语言中,Base64加密和解密可以通过Java的标准库Java 8及更高版本中的`java.util.Base64`类来实现。这个类提供了多种方法,可以方便地对字符串或字节数组进行Base64编码和解码。 首先,让我们看一下Base64...

Global site tag (gtag.js) - Google Analytics