java加密解密工具类

本文转自:http://blog.sina.com.cn/s/blog_684bceb901016cru.html

package com.xy6.tag;

import java.io.UnsupportedEncodingException;

public class Encode {
    public static final String ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()";

    public static String encode(String str){
         String enstr="";
         String ling="0000";
         char[] data=str.toCharArray();
            for (int i = 0; i < data.length; i++) {
                String unicode=Integer.toHexString(data[i]);
                enstr+=ling.substring(0, 4-unicode.length())+Integer.toHexString(data[i]);
            }
         return enstr;
    }

    public static String decode(String str){
         byte[] baKeyword = new byte[str.length()/2];
         for(int i = 0; i < baKeyword.length; i++)
         {
             try{
                 baKeyword[i] = (byte)(0xff & Integer.parseInt(str.substring(i*2, i*2+2),16));
             }catch(Exception e){
                 e.printStackTrace();
             }
         }
         try {
             str = new String(baKeyword, "utf-16");//UTF-16le:Not
         } catch (Exception e1)  {
             e1.printStackTrace();
         }
         return str;
    }


    public static String detialEncode(String sql){
        return sql.replaceAll("'", ":").replaceAll("  ", " ").replaceAll("%", "@");
    }
    public static String detialDecode(String sql){
        return sql.replaceAll(":", "'").replaceAll("@","%");
    }


    ////实现js encodeURI 效果
    public static String encodeURI(String input) {

        if (input == null || "".equals(input)) {

            return input;

        }



        int l = input.length();

        StringBuilder o = new StringBuilder(l * 3);

        try {

            for (int i = 0; i < l; i++) {

                String e = input.substring(i, i + 1);

                if (ALLOWED_CHARS.indexOf(e) == -1) {

                    byte[] b = e.getBytes("utf-8");

                    o.append(getHex(b));

                    continue;

                }

                o.append(e);

            }

            return o.toString();

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

        return input;

    }



    private static String getHex(byte buf[]) {

        StringBuilder o = new StringBuilder(buf.length * 3);

        for (int i = 0; i < buf.length; i++) {

            int n = (int) buf[i] & 0xff;

            o.append("%");

            if (n < 0x10) {

                o.append("0");

            }

            o.append(Long.toString(n, 16).toUpperCase());

        }

        return o.toString();

    }



    public static String dencodeURI(String encodedURI) {

        char actualChar;



        StringBuffer buffer = new StringBuffer();



        int bytePattern, sumb = 0;



        for (int i = 0, more = -1; i < encodedURI.length(); i++) {

            actualChar = encodedURI.charAt(i);



            switch (actualChar) {

            case '%': {

                actualChar = encodedURI.charAt(++i);

                int hb = (Character.isDigit(actualChar) ? actualChar - '0'

                        : 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;

                actualChar = encodedURI.charAt(++i);

                int lb = (Character.isDigit(actualChar) ? actualChar - '0'

                        : 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;

                bytePattern = (hb << 4) | lb;

                break;

            }

            case '+': {

                bytePattern = ' ';

                break;

            }

            default: {

                bytePattern = actualChar;

            }

            }



            if ((bytePattern & 0xc0) == 0x80) { // 10xxxxxx

                sumb = (sumb << 6) | (bytePattern & 0x3f);

                if (--more == 0)

                    buffer.append((char) sumb);

            } else if ((bytePattern & 0x80) == 0x00) { // 0xxxxxxx

                buffer.append((char) bytePattern);

            } else if ((bytePattern & 0xe0) == 0xc0) { // 110xxxxx

                sumb = bytePattern & 0x1f;

                more = 1;

            } else if ((bytePattern & 0xf0) == 0xe0) { // 1110xxxx

                sumb = bytePattern & 0x0f;

                more = 2;

            } else if ((bytePattern & 0xf8) == 0xf0) { // 11110xxx

                sumb = bytePattern & 0x07;

                more = 3;

            } else if ((bytePattern & 0xfc) == 0xf8) { // 111110xx

                sumb = bytePattern & 0x03;

                more = 4;

            } else { // 1111110x

                sumb = bytePattern & 0x01;

                more = 5;

            }

        }

        return buffer.toString();

    }
}


### Java 加密解密工具类Java中,`javax.crypto`包提供了多种加密解密的方法。下面是一个基于AES算法的简单加密解密工具类实现。 #### AES加解密工具类示例代码 ```java import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AesUtil { private static final String ALGORITHM = "AES"; private static final int KEY_SIZE = 128; // 可选值:128, 192 或者 256 /** * 生成密钥 */ public static String generateKey() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM); keyGen.init(KEY_SIZE); SecretKey secretKey = keyGen.generateKey(); return Base64.getEncoder().encodeToString(secretKey.getEncoded()); } /** * 加密方法 * * @param data 待加密数据 * @param key 密钥字符串 * @return 返回Base64编码后的加密数据 */ public static String encrypt(String data, String key) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encryptedData = cipher.doFinal(data.getBytes("UTF-8")); return Base64.getEncoder().encodeToString(encryptedData); } /** * 解密方法 * * @param encryptedData 已经被加密的数据(Base64编码) * @param key 密钥字符串 * @return 原始未加密数据 */ public static String decrypt(String encryptedData, String key) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] originalData = cipher.doFinal(Base64.getDecoder().decode(encryptedData)); return new String(originalData, "UTF-8"); } } ``` 此工具类实现了基本的功能,包括密钥生成、加密以及解密操作[^1]。通过调用这些静态方法可以方便地完成对敏感信息的安全处理工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值