工具类1: AES加密(Android项目中使用)

  1.  最近项目中用到自己公司开放平台上的AES加密,(针对密码要做加密),具体加密规则如下:

 

二、具体工具类如下,直接拿去用

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
/**
 *
 * @author xxx
 *
 *  Android AES加密
 *  填充:PKCS7Padding
 *  加密模式ECB
 *
 */

public class AESUtil {

    /**
     * encrypt input text
     *
     * @param password 密码
     * @param username 用户名,长度16(如果超过16位则截取前16位,不足16为后面补0)
     * @return
     */
    public static String encrypt(String password, String username) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(username.getBytes(), "AES");

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(password.getBytes());
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }

        return new String(Base64.encodeBase64(crypted));
    }

    /**
     * decrypt input text
     *
     * @param input
     * @param key
     * @return
     */
    public static String decrypt(String input, String key) {
        byte[] output = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
//            output = cipher.doFinal(Base64.decodeBase64(input));
            output = cipher.doFinal(Hex.decodeHex(input.toCharArray()));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return new String(output);
    }

}

  三、 使用中可以写一个测试例子验证下,结果验证可以直接去这个网站对比:线加密网址:http://tool.chacuo.net/cryptaes/

 

结语:欧了,完活!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值