|
| 1 | +package cn.aofeng.demo.encrypt; |
| 2 | + |
| 3 | +import static cn.aofeng.demo.util.LogUtil.log; |
| 4 | + |
| 5 | +import java.io.UnsupportedEncodingException; |
| 6 | +import java.security.InvalidAlgorithmParameterException; |
| 7 | +import java.security.InvalidKeyException; |
| 8 | +import java.security.NoSuchAlgorithmException; |
| 9 | + |
| 10 | +import javax.crypto.BadPaddingException; |
| 11 | +import javax.crypto.IllegalBlockSizeException; |
| 12 | +import javax.crypto.Mac; |
| 13 | +import javax.crypto.NoSuchPaddingException; |
| 14 | +import javax.crypto.SecretKey; |
| 15 | + |
| 16 | +import org.apache.commons.codec.binary.Base64; |
| 17 | + |
| 18 | +/** |
| 19 | + * HMAC-SHA1签名算法。 |
| 20 | + * |
| 21 | + * @author <a href="mailto:[email protected]">聂勇</a> |
| 22 | + */ |
| 23 | +public class HmacSha1 { |
| 24 | + |
| 25 | + public final String encryptType = "HmacSHA1"; |
| 26 | + public final String key = "abcdefgh_1234567"; |
| 27 | + |
| 28 | + public void execute(String data) throws UnsupportedEncodingException, |
| 29 | + NoSuchAlgorithmException, InvalidKeyException { |
| 30 | + EncryptAndDecrypt ead = new EncryptAndDecrypt(); |
| 31 | + |
| 32 | + byte[] srcData = data.getBytes(EncryptAndDecrypt.CHARSET); |
| 33 | + SecretKey secretKey = ead.createSecretKey(encryptType, key); // 生成密钥对象 |
| 34 | + Mac mac = Mac.getInstance(encryptType); |
| 35 | + mac.init(secretKey); |
| 36 | + byte[] result = mac.doFinal(srcData); |
| 37 | + |
| 38 | + log("使用%s签名后的数据:", encryptType); |
| 39 | + log(Base64.encodeBase64String(result)); |
| 40 | + } |
| 41 | + |
| 42 | + public static void main(String[] args) throws InvalidKeyException, |
| 43 | + UnsupportedEncodingException, IllegalBlockSizeException, |
| 44 | + BadPaddingException, NoSuchAlgorithmException, |
| 45 | + NoSuchPaddingException, InvalidAlgorithmParameterException { |
| 46 | + String data = "炎黄,汉字,english,do it,abcdefghijklmnopqrstuvwxyz,0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ, ~!@#$%^&*()_+=-"; |
| 47 | + log("待签名的数据:\n%s", data); |
| 48 | + |
| 49 | + HmacSha1 hs = new HmacSha1(); |
| 50 | + hs.execute(data); |
| 51 | + } |
| 52 | + |
| 53 | +} |
0 commit comments