001    package com.nimbusds.jose.crypto;
002    
003    
004    import net.jcip.annotations.ThreadSafe;
005    
006    import com.nimbusds.jose.JOSEException;
007    import com.nimbusds.jose.JWSSigner;
008    import com.nimbusds.jose.ReadOnlyJWSHeader;
009    import com.nimbusds.jose.util.Base64URL;
010    
011    
012    
013    /**
014     * Message Authentication Code (MAC) signer of 
015     * {@link com.nimbusds.jose.JWSObject JWS objects}. This class is thread-safe.
016     *
017     * <p>Supports the following JSON Web Algorithms (JWAs):
018     *
019     * <ul>
020     *     <li>{@link com.nimbusds.jose.JWSAlgorithm#HS256}
021     *     <li>{@link com.nimbusds.jose.JWSAlgorithm#HS384}
022     *     <li>{@link com.nimbusds.jose.JWSAlgorithm#HS512}
023     * </ul>
024     * 
025     * @author Vladimir Dzhuvinov
026     * @version $version$ (2013-05-16)
027     */
028    @ThreadSafe
029    public class MACSigner extends MACProvider implements JWSSigner {
030    
031    
032            /**
033             * Creates a new Message Authentication (MAC) signer.
034             *
035             * @param sharedSecret The shared secret. Must not be {@code null}.
036             */
037            public MACSigner(final byte[] sharedSecret) {
038    
039                    super(sharedSecret);
040            }
041    
042    
043            /**
044             * Creates a new Message Authentication (MAC) signer.
045             *
046             * @param sharedSecretString The shared secret as a UTF-8 encoded
047             *                           string. Must not be {@code null}.
048             */
049            public MACSigner(final String sharedSecretString) {
050    
051                    super(sharedSecretString);
052            }
053    
054    
055            @Override
056            public Base64URL sign(final ReadOnlyJWSHeader header, final byte[] signingInput)
057                    throws JOSEException {
058    
059                    String jcaAlg = getJCAAlgorithmName(header.getAlgorithm());
060    
061                    byte[] hmac = HMAC.compute(jcaAlg, getSharedSecret(), signingInput);
062    
063                    return Base64URL.encode(hmac);
064            }
065    }