两种加密的Java实现:MD5、AES

1、MD5加密

    public static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        log.debug("start EncoderByMd5 str:=" + str);

        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(str.getBytes());
        byte bytes[] = digest.digest();
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            if ((bytes[i] & 255) < 16)
                buf.append("0");
            buf.append(Long.toString(bytes[i] & 255, 16));
        }
        return buf.toString();
    }

2、AES加密

     public static byte[] encrypt(byte[] sSrc, String encryptionKey, String asepyl) throws Exception {
        if (encryptionKey == null) {
            return null;
        }
        byte[] raw = encryptionKey.getBytes(ENCODING);
        SecretKeySpec keySpec = new SecretKeySpec(raw, ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        IvParameterSpec initVector = new IvParameterSpec(asepyl.getBytes(), 0, 16);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, initVector);
        byte[] encrypted = cipher.doFinal(sSrc);
        return encrypted;
    }


    public static byte[] decrypt(byte[] sSrc, String sKey, String spec) throws Exception {
        if (sKey == null) {
            return null;
        }
        byte[] raw = sKey.getBytes(ENCODING);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, 0, 16, ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        IvParameterSpec initVector = new IvParameterSpec(spec.getBytes(), 0, 16);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, initVector);
        byte[] original = cipher.doFinal(sSrc);
        return original;
    }


    public static byte[] getFromBASE64(String s) {
        if (s == null)
            return null;
        byte[] b = null;
        try {
            b = org.apache.commons.codec.binary.Base64.decodeBase64(s.getBytes(ENCODING));
        } catch (UnsupportedEncodingException e) {
            logger.error("decodeBase64 出现异常", e);
        }
        return b;
    }


    public static byte[] getBASE64(byte[] contentBytes) {
        if (contentBytes == null)
            return null;
        byte[] base64EncodeBytes = null;
        base64EncodeBytes = org.apache.commons.codec.binary.Base64.encodeBase64(contentBytes);
        return base64EncodeBytes;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值