加密base64

 1 package com.lzkj.csp.bas.util;
 2 
 3 @SuppressWarnings("restriction")
 4 public class Base64Utils {
 5 
 6     private final static sun.misc.BASE64Encoder base64Encoder = new sun.misc.BASE64Encoder();
 7     private final static sun.misc.BASE64Decoder base64Decoder = new sun.misc.BASE64Decoder();
 8 
 9     /**
10      * Base64-encode the given byte array to a String.
11      *
12      * @param src the original byte array (may be {@code null})
13      * @return the encoded byte array as a UTF-8 String (or {@code null} if the
14      * input was {@code null})
15      */
16     public static String encodeToString(byte[] src) {
17         if (src == null)
18             return null;
19         return base64Encoder.encode(src);
20     }
21 
22     /**
23      * Base64-encode the given byte array to a String.
24      *
25      * @param src           the original byte array (may be {@code null})
26      * @param followRFC2045 true Encoded lines be no more than 76 characters long
27      *                      false Encoded lines be more than 76 characters long
28      * @return
29      * @see <a href="https://tools.ietf.org/html/rfc2045"/>
30      * @see <a href="https://en.wikipedia.org/wiki/Base64#MIME"/>
31      * @see <a href="https://en.wikipedia.org/wiki/Request_for_Comments"/>
32      */
33     public static String encodeToString(byte[] src, boolean followRFC2045) {
34         if (src == null)
35             return null;
36         String encode = base64Encoder.encode(src);
37         if (!followRFC2045) {
38             encode = encode.replaceAll(System.getProperty("line.separator"), "");
39         }
40         return encode;
41     }
42 
43     /**
44      * Base64-decode the given byte array from an UTF-8 String.
45      *
46      * @param src the encoded UTF-8 String (may be {@code null})
47      * @return the original byte array (or {@code null} if the input was
48      * {@code null})
49      */
50     public static byte[] decodeFromString(String src) {
51         if (src == null)
52             return null;
53         try {
54             byte[] decodeBuffer = base64Decoder.decodeBuffer(src);
55             return decodeBuffer;
56         } catch (Exception e) {
57             throw new RuntimeException("decodeFromString failed.", e);
58         }
59     }
60 }
说明:以上的工具类中加密方法(encodeToString)有两个,一个是普通的base64加遵循RFC2045机密规则,此规则在加密后的符76位自动添加换行符,所以在此工具类中重写了encodeToString(String src ,boolean followRFC2045),true:遵从、false:不遵从

猜你喜欢

转载自www.cnblogs.com/lxn0216/p/8961322.html