使用Java、JS 对数据进行base64 加解密(解决中文乱码)

文章目录

1、Java类

package com.esint.ztb.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.UnsupportedEncodingException;

//应对明文传输问题
public class Base64 {
   
	// 加密
	public static String encode(String str) {
   
		byte[] b = null;
		String s = null;
		try {
   
			b = str.getBytes("utf-8");
		} catch (UnsupportedEncodingException e) {
   
			e.printStackTrace();
		}
		if (b != null) {
   
			s = new BASE64Encoder().encode(b);
			//据RFC 822规定,每76个字符,还需要加上一个回车换行去掉换行符
			s = s.replaceAll("[\\s*\t\n\r]", "");  
		}
		return s;
	}
 
	// 解密
	public static String decode(String s) {
   
		byte[] b = null;
		String result = null;
		if (s != null) {
   
			BASE64Decoder decoder = new BASE64Decoder();
			try {
   
				b = decoder.decodeBuffer(s);
				result = new String(b, "utf-8");
			} catch (Exception e) {
   
				e.printStackTrace();
			}
		}
		return result;
	}
	//使用方法
	public static void main(String[] args){
   
		String s = "你好,The Word!";
		//System.out.println(s.length());
		String enStr = encode(s);
		String deStr = decode(enStr);
		System.out.println("原始数据:"+s+"\n加密数据:"+enStr+"\n解密数据:"+deStr);
	}
}

2、js

/*!
 * jquery.base64.js 0.1 - https://github.com/yckart/jquery.base64.js
 * Makes Base64 en & -decoding simpler as it is.
 *
 * Based upon: https://gist.github.com/Yaffle/1284012
 *
 * Copyright (c) 2012 Yannick Albert (http://yckart.com)
 * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
 * 2013/02/10
 **/
/**
 * Created by SLICE_30_K on 2017/5/22.
 *
 * 支持一般Base64的编码和解码
 * 支持符合RFC_4648标准中"URL and Filename Safe Alphabet"的URL安全Base64编解码
 * 支持中文字符的编解码(Unicode编码)
 */
;(function (root, factory) {
   
    if (typeof exports === "object") {
   
        // CommonJS
        module.exports = exports = factory();
    }
    else if (typeof define === "function" && define.amd) {
   
        // AMD
        define(factory);
    }
    else {
   
        // Global (browser)
        window.BASE64 = factory();
    }
}(this, function () {
   
    var BASE64_MAPPING = [
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
        'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会飞的小蜗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值