Java基于AES的加密与解密

基于AES的加密与解密,加密与解密都需要指定相关的key。


1、加密与解密代码

package com.ganymede.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * Created by wuke on 2016/11/1.
 */
public class EnAesCode {
    static private byte[] codes = new byte[256];
    private static final String ALGORITHM_KEY = "AES";
    private static final String ALGORITHM_ENCODING = "UTF-8";

    static {
        for (int i = 0; i < 256; i++)
            codes[i] = -1;
        for (int i = 'A'; i <= 'Z'; i++)
            codes[i] = (byte) (i - 'A');
        for (int i = 'a'; i <= 'z'; i++)
            codes[i] = (byte) (26 + i - 'a');
        for (int i = '0'; i <= '9'; i++)
            codes[i] = (byte) (52 + i - '0');
        codes['+'] = 62;
        codes['/'] = 63;
    }

    /**
     * 将base64编码的数据解码成原始数据
     *
     * @param data
     * @return
     */
    static public byte[] decode(byte[] data) {
        int len = ((data.length + 3) / 4) * 3;
        if (data.length > 0 & data[data.length - 1] == '=')
            --len;
        if (data.length > 1 & data[data.length - 2] == '=')
            --len;
        byte[] out = new byte[len];
        int shift = 0;
        int accum = 0;
        int index = 0;
        for (int ix = 0; ix < data.length; ix++) {
            int value = codes[data[ix] & 0xFF];
            if (value >= 0) {
                accum <<= 6;
                shift += 6;
                accum |= value;
                if (shift >= 8) {
                    shift -= 8;
                    out[index++] = (byte) ((accum >> shift) & 0xff);
                }
            }
        }
        if (index != out.length) {
            out = null;
        }

        return out;
    }


    /**
     * 解密字符串
     * 需提供相关密码
     *
     * @param content
     * @param strKey
     * @return
     */
    public static String decrypt(String content, String strKey) {
        try {
            byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
            SecretKey key = new SecretKeySpec(keyBytes, ALGORITHM_KEY);
            Cipher cipher = Cipher.getInstance(ALGORITHM_KEY);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] cleartext = decode(content.getBytes(ALGORITHM_ENCODING));
            byte[] ciphertextBytes = cipher.doFinal(cleartext);
            return new String(ciphertextBytes);

        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 加密字符串
     * 需提供相关密码
     *
     * @param mobile
     * @param strKey
     * @return
     */
    public static String encrypt(String mobile, String strKey) {
        if (mobile == null || "".equals(mobile)) {
            return mobile;
        }
        byte[] mobileKeyBytes = null;
        try {
            mobileKeyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] encryptBytes = enCode(mobile, mobileKeyBytes);

        if (encryptBytes == null) {
            // 加密报错了
            return mobile;
        }
        // 返回带特定标识的密文
        // 进行Base64编码
        return new StringBuilder("").append(Base64.encodeBase64String(encryptBytes)).toString().replaceAll("\n", "");

    }

    /**
     * AES加密
     *
     * @param clearText
     * @param keyBytes
     * @return
     */
    private static byte[] enCode(String clearText, byte[] keyBytes) {
        try {
            SecretKey key = new SecretKeySpec(keyBytes, ALGORITHM_KEY);
            Cipher cipher = Cipher.getInstance(ALGORITHM_KEY);
            cipher.init(Cipher.ENCRYPT_MODE, key);

            byte[] cleartext = clearText.getBytes(ALGORITHM_ENCODING);
            byte[] ciphertextBytes = cipher.doFinal(cleartext);

            return ciphertextBytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        String enCode = EnAesCode.encrypt("18912345678", "abc");
        System.out.println(enCode);

        String denCode = EnAesCode.decrypt(enCode, "abc");
        System.out.println(denCode);

    }
}


2、 项目的pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ganymede</groupId>
    <artifactId>javaee</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
    <dependencies>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
    </dependencies>


    <!-- maven官方 http://repo1.maven.org/maven2/  或 http://repo2.maven.org/maven2/ (延迟低一些) -->
    <repositories>
        <repository>
            <id>central</id>
            <name>Maven Repository Switchboard</name>
            <layout>default</layout>
            <url>http://repo2.maven.org/maven2</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>



3、加密与解密时,只要对应好相关的key就好,也不容易被破解。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值