java常用加密算法

在调用公有云的api时,通常会使用一些加密算法加密参数,下面给出java中常用加密算法:

package com.dayang.tencentapi.util;

import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Security
 * <p>
 * <p>
 * GENGJUN
 * created on 2016/3/17
 */
public class Security {

    /**
     * base64 encode
     * @param bytes bytes to be encoded
     * @return the encoded String
     */
    public static String encodeUrlComponent(byte[] bytes){
        String enComponent = null;
        try{
            enComponent = new BASE64Encoder().encode(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return enComponent;
    }

    /**
     *
     * @param secretkey secret key
     * @param text to encrypt
     * @return the encrypted bytes
     */
    public static byte[] hmacSha1(String secretkey, String text){
        byte[] result = null;

        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            Key key = new SecretKeySpec(secretkey.getBytes(), "HmacSHA1");
            mac.init(key);
            result = mac.doFinal(text.getBytes());
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *
     * @param text the string to encrypt
     * @return
     */
    public static String md5Encrypt(String text){
        if(text == null) return "";

        String result = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("sha-1");
            byte[] eBytes = messageDigest.digest(text.getBytes());
            result = hex(eBytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return result;
    }

    private static String hex(byte[] arr){
        if(arr == null){
            return "";
        }

        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < arr.length; i++){
            buffer.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1, 3));
        }

        return buffer.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值