Tuesday, January 15, 2013

计算 HMAC

如何使用 Java 计算数字签名。
import javax.crypto.KeyGenerator ;
import javax.crypto.Mac ;
import javax.crypto.SecretKey ;
import javax.crypto.spec.SecretKeySpec ;

import java.security.NoSuchAlgorithmException ;
import java.security.InvalidKeyException ;

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

public class TestHMAC {
    SecretKey key ;
    Mac mac ;

    public String getKey () {
 byte[] bin = key.getEncoded () ;
 byte[] ascii = Base64.encodeBase64 (bin) ;
 return new String (ascii) ;
    }

    public TestHMAC (String alg)
 throws NoSuchAlgorithmException, InvalidKeyException {
 KeyGenerator gen = KeyGenerator.getInstance (alg) ;
 key = gen.generateKey () ;
 mac = Mac.getInstance (key.getAlgorithm ()) ;
 mac.init (key) ;
    }

    public TestHMAC (String alg, String k)
 throws NoSuchAlgorithmException, InvalidKeyException {
 byte [] ascii = k.getBytes () ;
 byte [] c = Base64.decodeBase64 (k) ;
 key = new SecretKeySpec (c, alg) ;
 mac = Mac.getInstance (key.getAlgorithm ()) ;
 mac.init (key) ;
    }

    public byte[] hash (Object o) {
 byte[] c = o.toString ().getBytes () ;
 return mac.doFinal (c) ;
    }

    public String hashToAscii (Object o) {
 byte [] hash = hash (o) ;
 byte [] ascii = Base64.encodeBase64 (hash) ;
 return new String (ascii) ;
    }

}

No comments:

Post a Comment