Java Code Examples for javax.crypto.Mac

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project miso-lims, under directory /core/src/main/java/uk/ac/bbsrc/tgac/miso/core/security/.

Source file: PasswordCodecService.java

  25 
vote

/** 
 * Encrypt a plaintext String using a hmac_sha1 salt
 * @param key of type String
 * @param plaintext of type String
 * @return String the encrypted String of the given plaintext String
 * @throws SignatureException when the HMAC is unable to be generated
 */
public synchronized String encryptHMACSHA1(String key,String plaintext) throws java.security.SignatureException {
  String result;
  try {
    SecretKeySpec signingKey=new SecretKeySpec(key.getBytes(),"HmacSHA1");
    Mac mac=Mac.getInstance("HmacSHA1");
    mac.init(signingKey);
    byte[] rawHmac=mac.doFinal(plaintext.getBytes());
    result=new Base64().encodeToString(rawHmac);
  }
 catch (  Exception e) {
    throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
  }
  return result;
}
 

Example 2

From project aws-tvm-anonymous, under directory /src/com/amazonaws/tvm/.

Source file: Utilities.java

  22 
vote

public static String sign(String content,String key){
  try {
    byte[] data=content.getBytes(Constants.ENCODING_FORMAT);
    Mac mac=Mac.getInstance(Constants.SIGNATURE_METHOD);
    mac.init(new SecretKeySpec(key.getBytes(Constants.ENCODING_FORMAT),Constants.SIGNATURE_METHOD));
    byte[] signature=Base64.encodeBase64(mac.doFinal(data));
    return new String(signature,Constants.ENCODING_FORMAT);
  }
 catch (  Exception exception) {
    log.log(Level.SEVERE,"Exception during sign",exception);
  }
  return null;
}
 

Example 3

From project aws-tvm-identity, under directory /src/com/amazonaws/tvm/.

Source file: Utilities.java

  22 
vote

public static String sign(String content,String key){
  try {
    byte[] data=content.getBytes(Constants.ENCODING_FORMAT);
    Mac mac=Mac.getInstance(Constants.SIGNATURE_METHOD);
    mac.init(new SecretKeySpec(key.getBytes(Constants.ENCODING_FORMAT),Constants.SIGNATURE_METHOD));
    char[] signature=Hex.encodeHex(mac.doFinal(data));
    return new String(signature);
  }
 catch (  Exception exception) {
    log.log(Level.SEVERE,"Exception during sign",exception);
  }
  return null;
}
 

Example 4

From project crest, under directory /core/src/main/java/org/codegist/crest/security/oauth/v1/.

Source file: OAuthsV1.java

  22 
vote

private static String sign(OAuthToken consumerOAuthToken,OAuthToken accessOAuthToken,MethodType methodType,String url,List<EncodedPair> oauthParams) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
  List<EncodedPair> sorted=sortByNameAndValues(oauthParams);
  String signUri=constructRequestURL(url);
  String signParams=join(sorted,'&','=',false,false);
  String signature=consumerOAuthToken.getSecret() + "&" + accessOAuthToken.getSecret();
  Mac mac=Mac.getInstance(SIGN_METH_4_J);
  mac.init(new SecretKeySpec(signature.getBytes(ENC),SIGN_METH_4_J));
  String data=methodType.name() + "&" + encode(signUri,ENC)+ "&"+ encode(signParams,ENC);
  String encoded=new String(Base64.encodeToByte(mac.doFinal(data.getBytes(ENC))),ENC);
  LOGGER.debug("Signature[data=\"%s\",signature=\"%s\",result=\"%s\"]",data,signature,encoded);
  return encoded;
}
 

Example 5

From project encfs-java, under directory /src/main/java/org/mrpdaemon/sec/encfs/.

Source file: EncFSCrypto.java

  22 
vote

/** 
 * Create a new Mac object for the given key.
 * @param key Key to create a new Mac for.
 * @return New Mac object.
 * @throws InvalidKeyException Passed key is not valid
 * @throws EncFSUnsupportedException HMAC SHA-1 not supported by this runtime
 */
public static Mac newMac(Key key) throws InvalidKeyException, EncFSUnsupportedException {
  Mac hmac;
  try {
    hmac=Mac.getInstance("HmacSHA1");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new EncFSUnsupportedException(e);
  }
  SecretKeySpec hmacKey=new SecretKeySpec(key.getEncoded(),"HmacSHA1");
  hmac.init(hmacKey);
  return hmac;
}
 

Example 6

From project eucalyptus, under directory /clc/modules/axis2-transport/src/edu/ucsb/eucalyptus/transport/query/.

Source file: HMACQuerySecurityHandler.java

  22 
vote

protected String checkSignature(final String queryKey,final String subject) throws QuerySecurityException {
  SecretKeySpec signingKey=new SecretKeySpec(queryKey.getBytes(),Hashes.Mac.HmacSHA1.toString());
  try {
    Mac mac=Mac.getInstance(Hashes.Mac.HmacSHA1.toString());
    mac.init(signingKey);
    byte[] rawHmac=mac.doFinal(subject.getBytes());
    return Base64.encode(rawHmac).replaceAll("=","");
  }
 catch (  Exception e) {
    LOG.error(e,e);
    throw new QuerySecurityException("Failed to compute signature");
  }
}
 

Example 7

From project figgo, under directory /src/main/java/br/octahedron/figgo/modules/admin/util/.

Source file: Route53Util.java

  22 
vote

protected static String sign(String content,String key) throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IllegalStateException {
  Mac mac=Mac.getInstance(MAC_ALGORITHM);
  SecretKey skey=new SecretKeySpec(key.getBytes(),KEY_ALGORITHM);
  mac.init(skey);
  mac.update(content.getBytes());
  return new String(Base64.encodeBase64((mac.doFinal())));
}
 

Example 8

From project flazr, under directory /src/main/java/com/flazr/util/.

Source file: Utils.java

  22 
vote

public static byte[] sha256(final byte[] message,final byte[] key){
  final Mac mac;
  try {
    mac=Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key,"HmacSHA256"));
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
  return mac.doFinal(message);
}
 

Example 9

From project GeoBI, under directory /print/src/main/java/org/mapfish/print/map/readers/google/.

Source file: GoogleURLSigner.java

  22 
vote

public String signature(String resource) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException {
  SecretKeySpec sha1Key=new SecretKeySpec(key,"HmacSHA1");
  Mac mac=Mac.getInstance("HmacSHA1");
  mac.init(sha1Key);
  byte[] sigBytes=mac.doFinal(resource.getBytes());
  String signature=Base64.encodeBytes(sigBytes);
  signature=signature.replace('+','-');
  signature=signature.replace('/','_');
  return signature;
}
 

Example 10

From project JMaNGOS, under directory /Auth/src/main/java/org/jmangos/auth/network/crypt/.

Source file: Crypt.java

  22 
vote

/** 
 * Gets the key.
 * @param EncryptionKey the encryption key
 * @param key the key
 * @return the key
 */
private byte[] getKey(final byte[] EncryptionKey,final byte[] key){
  final SecretKeySpec ds=new SecretKeySpec(EncryptionKey,"HmacSHA1");
  Mac m;
  try {
    m=Mac.getInstance("HmacSHA1");
    m.init(ds);
    return m.doFinal(key);
  }
 catch (  final Exception e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 11

From project jPOS, under directory /jpos/src/main/java/org/jpos/security/jceadapter/.

Source file: JCEHandler.java

  22 
vote

/** 
 * Generates MAC (Message Message Authentication Code) for some data.
 * @param data the data to be MACed
 * @param kd the key used for MACing
 * @param macAlgorithm MAC algorithm name suitable for  {@link Mac#getInstance}
 * @return the MAC
 * @throws org.jpos.security.jceadapter.JCEHandlerException
 */
public byte[] generateMAC(byte[] data,Key kd,String macAlgorithm) throws JCEHandlerException {
  Mac mac=assignMACEngine(new MacEngineKey(macAlgorithm,kd));
synchronized (mac) {
    mac.reset();
    return mac.doFinal(data);
  }
}
 

Example 12

From project mapfish-print, under directory /src/main/java/org/mapfish/print/map/readers/google/.

Source file: GoogleURLSigner.java

  22 
vote

public String signature(String resource) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException {
  SecretKeySpec sha1Key=new SecretKeySpec(key,"HmacSHA1");
  Mac mac=Mac.getInstance("HmacSHA1");
  mac.init(sha1Key);
  byte[] sigBytes=mac.doFinal(resource.getBytes());
  String signature=Base64.encodeBytes(sigBytes);
  signature=signature.replace('+','-');
  signature=signature.replace('/','_');
  return signature;
}
 

Example 13

From project mapfish-print_1, under directory /src/main/java/org/mapfish/print/map/readers/google/.

Source file: GoogleURLSigner.java

  22 
vote

public String signature(String resource) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException {
  SecretKeySpec sha1Key=new SecretKeySpec(key,"HmacSHA1");
  Mac mac=Mac.getInstance("HmacSHA1");
  mac.init(sha1Key);
  byte[] sigBytes=mac.doFinal(resource.getBytes());
  String signature=Base64.encodeBytes(sigBytes);
  signature=signature.replace('+','-');
  signature=signature.replace('/','_');
  return signature;
}
 

Example 14

From project onebusaway-nyc, under directory /onebusaway-nyc-presentation/src/main/java/org/onebusaway/nyc/geocoder/impl/.

Source file: GoogleGeocoderImpl.java

  22 
vote

/** 
 * PRIVATE METHODS
 */
private String signRequest(String key,String resource) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException {
  key=key.replace('-','+');
  key=key.replace('_','/');
  byte[] base64edKey=Base64.decodeBase64(key.getBytes());
  SecretKeySpec sha1Key=new SecretKeySpec(base64edKey,"HmacSHA1");
  Mac mac=Mac.getInstance("HmacSHA1");
  mac.init(sha1Key);
  byte[] sigBytes=mac.doFinal(resource.getBytes());
  String signature=new String(Base64.encodeBase64(sigBytes));
  signature=signature.replace('+','-');
  signature=signature.replace('/','_');
  return resource + "&signature=" + signature;
}
 

Example 15

From project siena, under directory /source/src/main/java/siena/sdb/ws/.

Source file: SimpleDB.java

  22 
vote

private String sign(String data,String key){
  try {
    SecretKeySpec signingKey=new SecretKeySpec(key.getBytes(ENCODING),SIGNATURE_METHOD);
    Mac mac=Mac.getInstance(SIGNATURE_METHOD);
    mac.init(signingKey);
    byte[] rawHmac=mac.doFinal(data.getBytes(ENCODING));
    return Base64.encodeBytes(rawHmac);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 16

From project sms-backup-plus, under directory /src/com/zegoggles/smssync/.

Source file: XOAuthConsumer.java

  22 
vote

private String generateSig(HttpRequest request,HttpParameters requestParameters) throws Exception {
  String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
  byte[] keyBytes=keyString.getBytes(OAuth.ENCODING);
  SecretKey key=new SecretKeySpec(keyBytes,MAC_NAME);
  Mac mac=Mac.getInstance(MAC_NAME);
  mac.init(key);
  String sbs=new SignatureBaseString(request,requestParameters).generate();
  return base64(mac.doFinal(sbs.getBytes(OAuth.ENCODING)));
}
 

Example 17

From project sparsemapcontent, under directory /extensions/resource/src/main/java/uk/co/tfd/sm/authn/token/.

Source file: CookieTokenAuthenticationServiceImpl.java

  22 
vote

private String hash() throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException {
  Mac m=Mac.getInstance(KeyHolder.HMAC);
  m.init(getKey(keyId));
  m.update(message.getBytes(UTF_8));
  return new String(Base64.encodeBase64URLSafe(m.doFinal()));
}
 

Example 18

From project spring-security-oauth, under directory /spring-security-jwt/src/main/java/org/springframework/security/jwt/crypto/sign/.

Source file: MacSigner.java

  22 
vote

public byte[] sign(byte[] bytes){
  try {
    Mac mac=Mac.getInstance(algorithm);
    mac.init(key);
    return mac.doFinal(bytes);
  }
 catch (  GeneralSecurityException e) {
    throw new RuntimeException(e);
  }
}
 

Example 19

From project spring-social-facebook, under directory /spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/.

Source file: SignedRequestDecoder.java

  22 
vote

private byte[] encrypt(String base,String key){
  try {
    SecretKeySpec secretKeySpec=new SecretKeySpec(key.getBytes(),HMAC_SHA256_MAC_NAME);
    Mac mac=Mac.getInstance(HMAC_SHA256_MAC_NAME);
    mac.init(secretKeySpec);
    return mac.doFinal(base.getBytes());
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
  }
catch (  InvalidKeyException e) {
    throw new IllegalStateException(e);
  }
}
 

Example 20

From project springfaces, under directory /springfaces-mvc/src/main/java/org/springframework/springfaces/mvc/render/.

Source file: ClientFacesViewStateHandler.java

  22 
vote

private byte[] removeAndVerifyMac(SecretKey secretKey,byte[] bytes) throws Exception {
  Mac mac=getMac(secretKey);
  mac.update(bytes,32,bytes.length - 32);
  byte[] expected=mac.doFinal();
  for (int i=0; i < expected.length; i++) {
    Assert.state(bytes[i] == expected[i],"MAC does not match");
  }
  byte[] rtn=new byte[bytes.length - expected.length];
  System.arraycopy(bytes,32,rtn,0,rtn.length);
  return rtn;
}
 

Example 21

From project springside, under directory /modules/core/src/main/java/org/springside/modules/security/utils/.

Source file: Cryptos.java

  22 
vote

/** 
 * ???HMAC-SHA1?????????, ?????????,????20???.
 * @param input ????????????
 * @param key   HMAC-SHA1???
 */
public static byte[] hmacSha1(byte[] input,byte[] key){
  try {
    SecretKey secretKey=new SecretKeySpec(key,HMACSHA1);
    Mac mac=Mac.getInstance(HMACSHA1);
    mac.init(secretKey);
    return mac.doFinal(input);
  }
 catch (  GeneralSecurityException e) {
    throw Exceptions.unchecked(e);
  }
}
 

Example 22

From project springside4, under directory /modules/core/src/main/java/org/springside/modules/security/utils/.

Source file: Cryptos.java

  22 
vote

/** 
 * ???HMAC-SHA1?????????, ?????????,????20???.
 * @param input ????????????
 * @param key HMAC-SHA1???
 */
public static byte[] hmacSha1(byte[] input,byte[] key){
  try {
    SecretKey secretKey=new SecretKeySpec(key,HMACSHA1);
    Mac mac=Mac.getInstance(HMACSHA1);
    mac.init(secretKey);
    return mac.doFinal(input);
  }
 catch (  GeneralSecurityException e) {
    throw Exceptions.unchecked(e);
  }
}
 

Example 23

From project teatrove, under directory /teaapps/src/main/java/org/teatrove/teaapps/contexts/.

Source file: CryptoContext.java

  22 
vote

/** 
 * Computes RFC 2104-compliant HMAC signature.
 * @param data The data to be signed.
 * @param key The signing key.
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws java.security.SignatureException when signature generation fails
 */
public String calculateRFC2104HMAC(String data,String key) throws java.security.SignatureException {
  String result;
  try {
    SecretKeySpec signingKey=new SecretKeySpec(key.getBytes(),HMAC_SHA1_ALGORITHM);
    Mac mac=Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    byte[] rawHmac=mac.doFinal(data.getBytes());
    result=new String(Base64.encodeBase64(rawHmac));
  }
 catch (  Exception e) {
    throw new SignatureException("Failed to generate HMAC",e);
  }
  return result;
}
 

Example 24

From project TextSecure, under directory /src/org/thoughtcrime/securesms/crypto/.

Source file: AsymmetricMasterCipher.java

  22 
vote

private byte[] getDigestedBytes(byte[] secretBytes,int iteration){
  try {
    Mac mac=Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secretBytes,"HmacSHA256"));
    return mac.doFinal(Conversions.intToByteArray(iteration));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
catch (  java.security.InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 

Example 25

From project uaa, under directory /common/src/test/java/org/cloudfoundry/identity/uaa/authentication/.

Source file: RubyUserTokenTests.java

  22 
vote

private static byte[] sign(String username,long validUntil,SecretKey key){
  Mac mac;
  try {
    mac=Mac.getInstance("HMACSHA1");
    mac.init(key);
  }
 catch (  GeneralSecurityException e) {
    throw new RuntimeException("Failed to create and initialize MAC: ",e);
  }
  byte[] bytesToSign=Utf8.encode(username + validUntil);
  byte[] sig=mac.doFinal(bytesToSign);
  return sig;
}
 

Example 26

From project xmlcalabash1, under directory /src/com/xmlcalabash/library/.

Source file: Hash.java

  22 
vote

/** 
 * Computes RFC 2104-compliant HMAC signature. Copied/modified slightly from amazon.webservices.common.Signature Contributed by Henry Thompson, used with permission
 * @param data The data to be signed.
 * @param key The signing key.
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws XProcException exception when signature generation fails
 */
private static String hmac(String data,String key){
  String result="";
  try {
    SecretKeySpec signingKey=new SecretKeySpec(key.getBytes(),HMAC_SHA1_ALGORITHM);
    Mac mac=Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    byte[] rawHmac=mac.doFinal(data.getBytes());
    result=Base64.encodeBytes(rawHmac);
  }
 catch (  Exception e) {
    throw XProcException.dynamicError(36,"Failed to generate HMAC : " + e.getMessage());
  }
  return result;
}
 

Example 27

From project zirco-browser, under directory /src/org/emergent/android/weave/client/.

Source file: WeaveCryptoUtil.java

  22 
vote

private String createMac(Key secKey,String ciphertext) throws GeneralSecurityException {
  Mac mac=Mac.getInstance("HMACSHA256",PROVIDER_NAME);
  mac.init(secKey);
  byte[] hmacBytes=mac.doFinal(WeaveUtil.toAsciiBytes(ciphertext));
  return WeaveUtil.toAsciiString(Hex.encode(hmacBytes));
}
 

Example 28

From project ajah, under directory /ajah-crypto/src/main/java/com/ajah/crypto/.

Source file: Crypto.java

  21 
vote

/** 
 * Returns HmacSHA1 of input.
 * @param secret String to process.
 * @return Digest of hash.
 */
public static byte[] getHmacSha1(final byte[] secret){
  try {
    final String keyString=Config.i.get("crypto.key.hmacsha1",null);
    if (StringUtils.isBlank(keyString)) {
      throw new IllegalArgumentException("crypto.key.hmacsha1 not defined");
    }
    final SecretKey key=new SecretKeySpec(keyString.getBytes(),"HmacSHA1");
    final Mac m=Mac.getInstance("HmacSHA1");
    m.init(key);
    m.update(secret);
    return m.doFinal();
  }
 catch (  final NoSuchAlgorithmException e) {
    throw new UnsupportedOperationException(e);
  }
catch (  final InvalidKeyException e) {
    throw new UnsupportedOperationException(e);
  }
}
 

Example 29

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/oauth/signpost/signature/.

Source file: HmacSha1MessageSigner.java

  21 
vote

@Override public String sign(HttpRequest request,HttpParameters requestParams) throws OAuthMessageSignerException {
  try {
    String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
    byte[] keyBytes=keyString.getBytes(OAuth.ENCODING);
    SecretKey key=new SecretKeySpec(keyBytes,MAC_NAME);
    Mac mac=Mac.getInstance(MAC_NAME);
    mac.init(key);
    String sbs=new SignatureBaseString(request,requestParams).generate();
    OAuth.debugOut("SBS",sbs);
    byte[] text=sbs.getBytes(OAuth.ENCODING);
    return base64Encode(mac.doFinal(text)).trim();
  }
 catch (  GeneralSecurityException e) {
    throw new OAuthMessageSignerException(e);
  }
catch (  UnsupportedEncodingException e) {
    throw new OAuthMessageSignerException(e);
  }
}
 

Example 30

From project android_external_oauth, under directory /core/src/main/java/net/oauth/signature/.

Source file: HMAC_SHA1.java

  21 
vote

private byte[] computeSignature(String baseString) throws GeneralSecurityException, UnsupportedEncodingException {
  SecretKey key=null;
synchronized (this) {
    if (this.key == null) {
      String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
      byte[] keyBytes=keyString.getBytes(ENCODING);
      this.key=new SecretKeySpec(keyBytes,MAC_NAME);
    }
    key=this.key;
  }
  Mac mac=Mac.getInstance(MAC_NAME);
  mac.init(key);
  byte[] text=baseString.getBytes(ENCODING);
  return mac.doFinal(text);
}
 

Example 31

From project Android_Pusher, under directory /src/com/emorym/android_pusher/.

Source file: Pusher.java

  21 
vote

private String authenticate(String channelName){
  if (!isConnected()) {
    Log.e(LOG_TAG,"pusher not connected, can't create auth string");
    return null;
  }
  try {
    String stringToSign=mSocketId + ":" + channelName;
    SecretKey key=new SecretKeySpec(mPusherSecret.getBytes(),PUSHER_AUTH_ALGORITHM);
    Mac mac=Mac.getInstance(PUSHER_AUTH_ALGORITHM);
    mac.init(key);
    byte[] signature=mac.doFinal(stringToSign.getBytes());
    StringBuffer sb=new StringBuffer();
    for (int i=0; i < signature.length; ++i) {
      sb.append(Integer.toHexString((signature[i] >> 4) & 0xf));
      sb.append(Integer.toHexString(signature[i] & 0xf));
    }
    String authInfo=mPusherKey + ":" + sb.toString();
    Log.d(LOG_TAG,"Auth Info " + authInfo);
    return authInfo;
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
catch (  InvalidKeyException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 32

From project BombusLime, under directory /src/org/bombusim/sasl/.

Source file: SASL_ScramSha1.java

  21 
vote

private byte[] Hi(byte[] str,byte[] salt,int i){
  byte[] dest;
  Mac hmac=getHMAC(str);
  hmac.update(salt);
  hmac.update((byte)0);
  hmac.update((byte)0);
  hmac.update((byte)0);
  hmac.update((byte)1);
  byte[] U=hmac.doFinal();
  dest=U.clone();
  i--;
  while (i > 0) {
    U=hmac.doFinal(U);
    xorB(dest,U);
    i--;
  }
  return dest;
}
 

Example 33

From project FlipDroid, under directory /lib/weibo4j/src/weibo4j/http/.

Source file: OAuth.java

  21 
vote

/** 
 * Computes RFC 2104-compliant HMAC signature.
 * @param data the data to be signed
 * @return signature
 * @see <a href="http://oauth.net/core/1.0/#rfc.section.9.2.1">OAuth Core - 9.2.1.  Generating Signature</a>
 */
String generateSignature(String data,OAuthToken token){
  byte[] byteHMAC=null;
  try {
    Mac mac=Mac.getInstance(HMAC_SHA1);
    SecretKeySpec spec;
    if (null == token) {
      String oauthSignature=encode(consumerSecret) + "&";
      spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
    }
 else {
      if (null == token.getSecretKeySpec()) {
        String oauthSignature=encode(consumerSecret) + "&" + encode(token.getTokenSecret());
        spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
        token.setSecretKeySpec(spec);
      }
      spec=token.getSecretKeySpec();
    }
    mac.init(spec);
    byteHMAC=mac.doFinal(data.getBytes());
  }
 catch (  InvalidKeyException e) {
    e.printStackTrace();
  }
catch (  NoSuchAlgorithmException ignore) {
  }
  return new BASE64Encoder().encode(byteHMAC);
}
 

Example 34

From project gengweibo, under directory /src/net/oauth/signature/.

Source file: HMAC_SHA1.java

  21 
vote

private byte[] computeSignature(String baseString) throws GeneralSecurityException, UnsupportedEncodingException {
  SecretKey key=null;
synchronized (this) {
    if (this.key == null) {
      String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
      byte[] keyBytes=keyString.getBytes(ENCODING);
      this.key=new SecretKeySpec(keyBytes,MAC_NAME);
    }
    key=this.key;
  }
  Mac mac=Mac.getInstance(MAC_NAME);
  mac.init(key);
  byte[] text=baseString.getBytes(ENCODING);
  return mac.doFinal(text);
}
 

Example 35

From project isohealth, under directory /Oauth/java/core/commons/src/main/java/net/oauth/signature/.

Source file: HMAC_SHA1.java

  21 
vote

private byte[] computeSignature(String baseString) throws GeneralSecurityException, UnsupportedEncodingException {
  SecretKey key=null;
synchronized (this) {
    if (this.key == null) {
      String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
      byte[] keyBytes=keyString.getBytes(ENCODING);
      this.key=new SecretKeySpec(keyBytes,MAC_NAME);
    }
    key=this.key;
  }
  Mac mac=Mac.getInstance(MAC_NAME);
  mac.init(key);
  byte[] text=baseString.getBytes(ENCODING);
  return mac.doFinal(text);
}
 

Example 36

From project java_binding_v1, under directory /src/com/tripit/auth/.

Source file: OAuthCredential.java

  21 
vote

private String generateSignature(String baseUrl,SortedMap<String,String> args) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
  String encoding="UTF-8";
  baseUrl=URLEncoder.encode(baseUrl,encoding);
  StringBuilder sb=new StringBuilder();
  boolean isFirst=true;
  for (  Map.Entry<String,String> arg : args.entrySet()) {
    if (isFirst) {
      isFirst=false;
    }
 else {
      sb.append('&');
    }
    sb.append(URLEncoder.encode(arg.getKey(),encoding));
    sb.append('=');
    sb.append(URLEncoder.encode(arg.getValue(),encoding));
  }
  String parameters=URLEncoder.encode(sb.toString(),encoding);
  String signatureBaseString="GET&" + baseUrl + "&"+ parameters;
  String key=(consumerSecret != null ? consumerSecret : "") + "&" + (userSecret != null ? userSecret : "");
  String macName="HmacSHA1";
  Mac mac=Mac.getInstance(macName);
  mac.init(new SecretKeySpec(key.getBytes(encoding),macName));
  byte[] signature=mac.doFinal(signatureBaseString.getBytes(encoding));
  return new Base64().encodeToString(signature).trim();
}
 

Example 37

From project jboss-sasl, under directory /src/main/java/org/jboss/sasl/digest/.

Source file: DigestMD5Base.java

  21 
vote

/** 
 * Generates MAC to be appended onto out-going messages.
 * @param Ki A non-null byte array containing the key for the digest
 * @param seqnum A non-null byte array contain the sequence number
 * @param msg  The message to be digested
 * @param start The offset from which to read the msg byte array
 * @param len The non-zero number of bytes to be read from the offset
 * @return The MAC of a message.
 * @throws javax.security.sasl.SaslException if an error occurs when generating MAC.
 */
protected byte[] getHMAC(byte[] Ki,byte[] seqnum,byte[] msg,int start,int len) throws SaslException {
  byte[] seqAndMsg=new byte[4 + len];
  System.arraycopy(seqnum,0,seqAndMsg,0,4);
  System.arraycopy(msg,start,seqAndMsg,4,len);
  try {
    SecretKey keyKi=new SecretKeySpec(Ki,"HmacMD5");
    Mac m=Mac.getInstance("HmacMD5");
    m.init(keyKi);
    m.update(seqAndMsg);
    byte[] hMAC_MD5=m.doFinal();
    byte macBuffer[]=new byte[10];
    System.arraycopy(hMAC_MD5,0,macBuffer,0,10);
    return macBuffer;
  }
 catch (  InvalidKeyException e) {
    throw new SaslException("DIGEST-MD5: Invalid bytes used for " + "key of HMAC-MD5 hash.",e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new SaslException("DIGEST-MD5: Error creating " + "instance of MD5 digest algorithm",e);
  }
}
 

Example 38

From project JGit, under directory /org.spearce.jgit/src/org/spearce/jgit/transport/.

Source file: AmazonS3.java

  21 
vote

private void authorize(final HttpURLConnection c) throws IOException {
  final Map<String,List<String>> reqHdr=c.getRequestProperties();
  final SortedMap<String,String> sigHdr=new TreeMap<String,String>();
  for (  final Map.Entry<String,List<String>> entry : reqHdr.entrySet()) {
    final String hdr=entry.getKey();
    if (isSignedHeader(hdr))     sigHdr.put(hdr.toLowerCase(),toCleanString(entry.getValue()));
  }
  final StringBuilder s=new StringBuilder();
  s.append(c.getRequestMethod());
  s.append('\n');
  s.append(remove(sigHdr,"content-md5"));
  s.append('\n');
  s.append(remove(sigHdr,"content-type"));
  s.append('\n');
  s.append(remove(sigHdr,"date"));
  s.append('\n');
  for (  final Map.Entry<String,String> e : sigHdr.entrySet()) {
    s.append(e.getKey());
    s.append(':');
    s.append(e.getValue());
    s.append('\n');
  }
  final String host=c.getURL().getHost();
  s.append('/');
  s.append(host.substring(0,host.length() - DOMAIN.length() - 1));
  s.append(c.getURL().getPath());
  final String sec;
  try {
    final Mac m=Mac.getInstance(HMAC);
    m.init(privateKey);
    sec=Base64.encodeBytes(m.doFinal(s.toString().getBytes("UTF-8")));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IOException("No " + HMAC + " support:"+ e.getMessage());
  }
catch (  InvalidKeyException e) {
    throw new IOException("Invalid key: " + e.getMessage());
  }
  c.setRequestProperty("Authorization","AWS " + publicKey + ":"+ sec);
}
 

Example 39

From project jmeter-components, under directory /src/main/java/com/atlantbh/jmeter/plugins/oauth/.

Source file: OAuthGenerator.java

  21 
vote

private Mac getMac(String consumerSecret){
  try {
    SecretKey key=new SecretKeySpec((consumerSecret + '&').getBytes(UTF_8),MAC_NAME);
    Mac result=Mac.getInstance(MAC_NAME);
    result.init(key);
    return result;
  }
 catch (  UnsupportedEncodingException e) {
    log.log(Level.SEVERE,"This exception should never ocurr!",e);
  }
catch (  NoSuchAlgorithmException e) {
    log.log(Level.SEVERE,"This exception should never ocurr!",e);
  }
catch (  InvalidKeyException e) {
    log.log(Level.SEVERE,"The key used to initialize MAC algorithm is invalid.",e);
  }
  return null;
}
 

Example 40

From project Karotz-Plugin, under directory /src/main/java/org/jenkinsci/plugins/karotz/.

Source file: KarotzUtil.java

  21 
vote

/** 
 * Creates HmacSha1.
 * @param secretKey SecretKey
 * @param data target data
 * @return HmacSha1
 * @throws KarotzException Illegal encoding.
 */
public static String doHmacSha1(String secretKey,String data) throws KarotzException {
  String hmacSha1;
  try {
    Mac mac=Mac.getInstance("HmacSHA1");
    SecretKeySpec secret=new SecretKeySpec(secretKey.getBytes("ASCII"),"HmacSHA1");
    mac.init(secret);
    byte[] digest=mac.doFinal(data.getBytes("UTF-8"));
    hmacSha1=new String(Base64.encodeBase64(digest),"ASCII");
  }
 catch (  IllegalStateException e) {
    throw new KarotzException(e);
  }
catch (  InvalidKeyException e) {
    throw new KarotzException(e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new KarotzException(e);
  }
catch (  UnsupportedEncodingException e) {
    throw new KarotzException(e);
  }
  return hmacSha1;
}
 

Example 41

From project NFCShopping, under directory /mobile phone client/NFCShopping/src/weibo4android/http/.

Source file: OAuth.java

  21 
vote

/** 
 * Computes RFC 2104-compliant HMAC signature.
 * @param data the data to be signed
 * @return signature
 * @see <a href="http://oauth.net/core/1.0/#rfc.section.9.2.1">OAuth Core - 9.2.1.  Generating Signature</a>
 */
String generateSignature(String data,OAuthToken token){
  byte[] byteHMAC=null;
  try {
    Mac mac=Mac.getInstance(HMAC_SHA1);
    SecretKeySpec spec;
    if (null == token) {
      String oauthSignature=encode(consumerSecret) + "&";
      spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
    }
 else {
      if (null == token.getSecretKeySpec()) {
        String oauthSignature=encode(consumerSecret) + "&" + encode(token.getTokenSecret());
        spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
        token.setSecretKeySpec(spec);
      }
      spec=token.getSecretKeySpec();
    }
    mac.init(spec);
    byteHMAC=mac.doFinal(data.getBytes());
  }
 catch (  InvalidKeyException e) {
    e.printStackTrace();
  }
catch (  NoSuchAlgorithmException ignore) {
  }
  return new BASE64Encoder().encode(byteHMAC);
}
 

Example 42

From project OAuth2Android, under directory /src/org/gerstner/oauth2android/token/.

Source file: MacTokenTypeDefinition.java

  21 
vote

private static String calculateMAC(String key,String normalizedString,String algorithm){
  String macString="";
  try {
    System.out.println("algorithm=" + algorithm);
    Mac mac=Mac.getInstance(algorithm);
    mac.init(new SecretKeySpec(key.getBytes(),algorithm));
    macString=Base64.encodeToString(mac.doFinal(normalizedString.getBytes()),Base64.DEFAULT);
  }
 catch (  InvalidKeyException ex) {
    Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE,null,ex);
  }
catch (  NoSuchAlgorithmException ex) {
    Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE,null,ex);
  }
  return macString;
}
 

Example 43

From project obpro_team_p, under directory /twitter/twitter4j-core/src/main/java/twitter4j/auth/.

Source file: OAuthAuthorization.java

  21 
vote

/** 
 * Computes RFC 2104-compliant HMAC signature.
 * @param data  the data to be signed
 * @param token the token
 * @return signature
 * @see <a href="http://oauth.net/core/1.0a/#rfc.section.9.2.1">OAuth Core - 9.2.1.  Generating Signature</a>
 */
String generateSignature(String data,OAuthToken token){
  byte[] byteHMAC=null;
  try {
    Mac mac=Mac.getInstance(HMAC_SHA1);
    SecretKeySpec spec;
    if (null == token) {
      String oauthSignature=HttpParameter.encode(consumerSecret) + "&";
      spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
    }
 else {
      spec=token.getSecretKeySpec();
      if (null == spec) {
        String oauthSignature=HttpParameter.encode(consumerSecret) + "&" + HttpParameter.encode(token.getTokenSecret());
        spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
        token.setSecretKeySpec(spec);
      }
    }
    mac.init(spec);
    byteHMAC=mac.doFinal(data.getBytes());
  }
 catch (  InvalidKeyException ike) {
    logger.error("Failed initialize \"Message Authentication Code\" (MAC)",ike);
    throw new AssertionError(ike);
  }
catch (  NoSuchAlgorithmException nsae) {
    logger.error("Failed to get HmacSHA1 \"Message Authentication Code\" (MAC)",nsae);
    throw new AssertionError(nsae);
  }
  return BASE64Encoder.encode(byteHMAC);
}
 

Example 44

From project platform_external_oauth, under directory /core/src/main/java/net/oauth/signature/.

Source file: HMAC_SHA1.java

  21 
vote

private byte[] computeSignature(String baseString) throws GeneralSecurityException, UnsupportedEncodingException {
  SecretKey key=null;
synchronized (this) {
    if (this.key == null) {
      String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
      byte[] keyBytes=keyString.getBytes(ENCODING);
      this.key=new SecretKeySpec(keyBytes,MAC_NAME);
    }
    key=this.key;
  }
  Mac mac=Mac.getInstance(MAC_NAME);
  mac.init(key);
  byte[] text=baseString.getBytes(ENCODING);
  return mac.doFinal(text);
}
 

Example 45

From project playframework-oauthprovider, under directory /app/net/oauth/signature/.

Source file: HMAC_SHA1.java

  21 
vote

/** 
 * Compute signature.
 * @param baseString the base string
 * @return the byte[]
 * @throws GeneralSecurityException the general security exception
 * @throws UnsupportedEncodingException the unsupported encoding exception
 */
private byte[] computeSignature(String baseString) throws GeneralSecurityException, UnsupportedEncodingException {
  SecretKey key=null;
synchronized (this) {
    if (this.key == null) {
      String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
      byte[] keyBytes=keyString.getBytes(ENCODING);
      this.key=new SecretKeySpec(keyBytes,MAC_NAME);
    }
    key=this.key;
  }
  Mac mac=Mac.getInstance(MAC_NAME);
  mac.init(key);
  byte[] text=baseString.getBytes(ENCODING);
  return mac.doFinal(text);
}
 

Example 46

From project red5-mavenized, under directory /red5_base/src/main/java/org/red5/server/crypto/.

Source file: HMAC.java

  21 
vote

/** 
 * compute the MAC from the member arrays keyBytes and the dataBytes. Return the MAC.
 * @return the MAC
 */
public byte[] computeMac(){
  Mac hm=null;
  byte[] result=null;
  if (log.isDebugEnabled()) {
    log.debug("Key data: {}",byteArrayToHex(keyBytes));
    log.debug("Hash data: {}",byteArrayToHex(dataBytes));
    log.debug("Algorithm: {}",ALGORITHM_ID);
  }
  try {
    hm=Mac.getInstance(ALGORITHM_ID);
    Key k1=new SecretKeySpec(keyBytes,0,keyBytes.length,ALGORITHM_ID);
    hm.init(k1);
    result=hm.doFinal(dataBytes);
  }
 catch (  Exception e) {
    log.warn("Bad algorithm or crypto library problem",e);
  }
  return result;
}
 

Example 47

From project RS-MVC, under directory /core/src/main/java/cx/ath/mancel01/restmvc/.

Source file: Session.java

  21 
vote

public static String sign(String message){
  byte[] key=privatekey.getBytes();
  if (key.length == 0) {
    return message;
  }
  try {
    Mac mac=Mac.getInstance("HmacSHA1");
    SecretKeySpec signingKey=new SecretKeySpec(key,"HmacSHA1");
    mac.init(signingKey);
    byte[] messageBytes=message.getBytes("utf-8");
    byte[] result=mac.doFinal(messageBytes);
    int len=result.length;
    char[] hexChars=new char[len * 2];
    for (int charIndex=0, startIndex=0; charIndex < hexChars.length; ) {
      int bite=result[startIndex++] & 0xff;
      hexChars[charIndex++]=HEX_CHARS[bite >> 4];
      hexChars[charIndex++]=HEX_CHARS[bite & 0xf];
    }
    return new String(hexChars);
  }
 catch (  Exception ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 48

From project sauce-ondemand-plugin, under directory /src/main/java/hudson/plugins/sauce_ondemand/.

Source file: SauceOnDemandReport.java

  21 
vote

public String getAuth() throws IOException {
  try {
    Calendar calendar=Calendar.getInstance();
    SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd-HH");
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    String key=PluginImpl.get().getUsername() + ":" + PluginImpl.get().getApiKey()+ ":"+ format.format(calendar.getTime());
    byte[] keyBytes=key.getBytes();
    SecretKeySpec sks=new SecretKeySpec(keyBytes,HMAC_KEY);
    Mac mac=Mac.getInstance(sks.getAlgorithm());
    mac.init(sks);
    byte[] hmacBytes=mac.doFinal(id.getBytes());
    byte[] hexBytes=new Hex().encode(hmacBytes);
    return new String(hexBytes,"ISO-8859-1");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IOException("Could not generate Sauce-OnDemand access code",e);
  }
catch (  InvalidKeyException e) {
    throw new IOException("Could not generate Sauce-OnDemand access code",e);
  }
catch (  UnsupportedEncodingException e) {
    throw new IOException("Could not generate Sauce-OnDemand access code",e);
  }
}
 

Example 49

From project signpost, under directory /signpost-core/src/main/java/oauth/signpost/signature/.

Source file: HmacSha1MessageSigner.java

  21 
vote

@Override public String sign(HttpRequest request,HttpParameters requestParams) throws OAuthMessageSignerException {
  try {
    String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
    byte[] keyBytes=keyString.getBytes(OAuth.ENCODING);
    SecretKey key=new SecretKeySpec(keyBytes,MAC_NAME);
    Mac mac=Mac.getInstance(MAC_NAME);
    mac.init(key);
    String sbs=new SignatureBaseString(request,requestParams).generate();
    OAuth.debugOut("SBS",sbs);
    byte[] text=sbs.getBytes(OAuth.ENCODING);
    return base64Encode(mac.doFinal(text)).trim();
  }
 catch (  GeneralSecurityException e) {
    throw new OAuthMessageSignerException(e);
  }
catch (  UnsupportedEncodingException e) {
    throw new OAuthMessageSignerException(e);
  }
}
 

Example 50

From project spring-social, under directory /spring-social-core/src/main/java/org/springframework/social/oauth1/.

Source file: SigningSupport.java

  21 
vote

private String sign(String signatureBaseString,String key){
  try {
    Mac mac=Mac.getInstance(HMAC_SHA1_MAC_NAME);
    SecretKeySpec spec=new SecretKeySpec(key.getBytes(),HMAC_SHA1_MAC_NAME);
    mac.init(spec);
    byte[] text=signatureBaseString.getBytes(UTF8_CHARSET_NAME);
    byte[] signatureBytes=mac.doFinal(text);
    signatureBytes=Base64.encode(signatureBytes);
    String signature=new String(signatureBytes,UTF8_CHARSET_NAME);
    return signature;
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
  }
catch (  InvalidKeyException e) {
    throw new IllegalStateException(e);
  }
catch (  UnsupportedEncodingException shouldntHappen) {
    throw new IllegalStateException(shouldntHappen);
  }
}
 

Example 51

From project stackmob-java-client-sdk, under directory /src/main/java/com/stackmob/sdk/api/.

Source file: StackMobSession.java

  21 
vote

public String generateMacToken(String method,String uri,String host,String port){
  String ts=String.valueOf(new Date().getTime() / 1000);
  String nonce=String.format("n%d",Math.round(Math.random() * 10000));
  try {
    String baseString=getNormalizedRequestString(ts,nonce,method,uri,host,port);
    Mac mac=Mac.getInstance(SIGNATURE_ALGORITHM);
    SecretKeySpec spec=new SecretKeySpec(oauth2MacKey.getBytes(),SIGNATURE_ALGORITHM);
    try {
      mac.init(spec);
    }
 catch (    InvalidKeyException ike) {
      throw new IllegalStateException(ike);
    }
    byte[] rawMacBytes=mac.doFinal(baseString.getBytes());
    byte[] b64Bytes=Base64.encodeBase64(rawMacBytes);
    String calculatedMac=new String(b64Bytes);
    return String.format("MAC id=\"%s\",ts=\"%s\",nonce=\"%s\",mac=\"%s\"",oauth2Token,ts,nonce,calculatedMac);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException("This device doesn't have SHA1");
  }
}
 

Example 52

From project twitter-2-weibo, under directory /core/src/main/java/weibo4j/.

Source file: Oauth.java

  21 
vote

public String parseSignedRequest(String signed_request) throws IOException, InvalidKeyException, NoSuchAlgorithmException {
  String[] t=signed_request.split("\\.",2);
  int padding=(4 - t[0].length() % 4);
  for (int i=0; i < padding; i++)   t[0]+="=";
  String part1=t[0].replace("-","+").replace("_","/");
  SecretKey key=new SecretKeySpec(WeiboConfig.getValue("client_SERCRET").getBytes(),"hmacSHA256");
  Mac m;
  m=Mac.getInstance("hmacSHA256");
  m.init(key);
  m.update(t[1].getBytes());
  String part1Expect=BASE64Encoder.encode(m.doFinal());
  sun.misc.BASE64Decoder decode=new sun.misc.BASE64Decoder();
  String s=new String(decode.decodeBuffer(t[1]));
  if (part1.equals(part1Expect)) {
    return ts(s);
  }
 else {
    return null;
  }
}
 

Example 53

From project twitter4j_1, under directory /twitter4j-core/src/main/java/twitter4j/auth/.

Source file: OAuthAuthorization.java

  21 
vote

/** 
 * Computes RFC 2104-compliant HMAC signature.
 * @param data  the data to be signed
 * @param token the token
 * @return signature
 * @see <a href="http://oauth.net/core/1.0a/#rfc.section.9.2.1">OAuth Core - 9.2.1.  Generating Signature</a>
 */
String generateSignature(String data,OAuthToken token){
  byte[] byteHMAC=null;
  try {
    Mac mac=Mac.getInstance(HMAC_SHA1);
    SecretKeySpec spec;
    if (null == token) {
      String oauthSignature=HttpParameter.encode(consumerSecret) + "&";
      spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
    }
 else {
      spec=token.getSecretKeySpec();
      if (null == spec) {
        String oauthSignature=HttpParameter.encode(consumerSecret) + "&" + HttpParameter.encode(token.getTokenSecret());
        spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
        token.setSecretKeySpec(spec);
      }
    }
    mac.init(spec);
    byteHMAC=mac.doFinal(data.getBytes());
  }
 catch (  InvalidKeyException ike) {
    logger.error("Failed initialize \"Message Authentication Code\" (MAC)",ike);
    throw new AssertionError(ike);
  }
catch (  NoSuchAlgorithmException nsae) {
    logger.error("Failed to get HmacSHA1 \"Message Authentication Code\" (MAC)",nsae);
    throw new AssertionError(nsae);
  }
  return BASE64Encoder.encode(byteHMAC);
}
 

Example 54

From project vash, under directory /src/vash/.

Source file: Seed.java

  21 
vote

SeedProviderHVAC(byte[] saltBytes,InputStream seedStream) throws NoSuchAlgorithmException, IOException {
  if (saltBytes != null && saltBytes.length != SALT_SIZE) {
    throw new InvalidSaltException("The salt for algorithm 2 must be 64 bytes long.");
  }
  Mac macXTR=Mac.getInstance(XTR_ALGORITHM);
  if (saltBytes == null) {
    saltBytes=DEFAULT_SALT;
  }
  SecretKeySpec salt=new SecretKeySpec(saltBytes,XTR_ALGORITHM);
  try {
    macXTR.init(salt);
  }
 catch (  InvalidKeyException e) {
    throw new InvalidSaltException(e.toString());
  }
  int cnt=0;
  byte[] buffer=new byte[4096];
  while (cnt != -1) {
    cnt=seedStream.read(buffer);
    if (cnt == -1) {
      break;
    }
    macXTR.update(buffer,0,cnt);
  }
  byte[] prkBase=macXTR.doFinal();
  SecretKeySpec prk=new SecretKeySpec(prkBase,0,PRF_SIZE,PRF_ALGORITHM);
  hmacExpand=Mac.getInstance(PRF_ALGORITHM);
  try {
    hmacExpand.init(prk);
  }
 catch (  InvalidKeyException e) {
    System.err.println(e.toString());
    System.exit(1);
  }
  Tbits=new BitSet(PRF_SIZE * 8);
  Tbitpos=0;
  Tcurrent=new byte[PRF_SIZE];
  Toffset=0;
  nextT();
}
 

Example 55

From project mina-sshd, under directory /sshd-core/src/main/java/org/apache/sshd/common/util/.

Source file: SecurityUtils.java

  19 
vote

public static synchronized Mac getMac(String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
  register();
  if (getSecurityProvider() == null) {
    return Mac.getInstance(algorithm);
  }
 else {
    return Mac.getInstance(algorithm,getSecurityProvider());
  }
}
 

Example 56

From project OpenID-Connect-Java-Spring-Server, under directory /openid-connect-common/src/main/java/org/mitre/jwt/signer/impl/.

Source file: HmacSigner.java

  19 
vote

private void initializeMac(){
  if (mac == null) {
    try {
      mac=Mac.getInstance(getAlgorithm().getStandardName());
    }
 catch (    NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
  }
}
 

Example 57

From project Red5, under directory /src/org/red5/server/net/rtmp/.

Source file: RTMPHandshake.java

  19 
vote

public RTMPHandshake(){
  log.trace("Handshake ctor");
  try {
    hmacSHA256=Mac.getInstance("HmacSHA256");
  }
 catch (  SecurityException e) {
    log.error("Security exception when getting HMAC",e);
  }
catch (  NoSuchAlgorithmException e) {
    log.error("HMAC SHA256 does not exist");
  }
  createHandshakeBytes();
}
 

Example 58

From project red5-server, under directory /src/org/red5/server/net/rtmp/.

Source file: RTMPHandshake.java

  19 
vote

public RTMPHandshake(){
  log.debug("Handshake ctor");
  try {
    hmacSHA256=Mac.getInstance("HmacSHA256");
  }
 catch (  SecurityException e) {
    log.error("Security exception when getting HMAC",e);
  }
catch (  NoSuchAlgorithmException e) {
    log.error("HMAC SHA256 does not exist");
  }
  createHandshakeBytes();
}
 

Example 59

From project security, under directory /impl/src/main/java/org/jboss/seam/security/crypto/.

Source file: MacBasedPRF.java

  19 
vote

/** 
 * Create Mac-based Pseudo Random Function.
 * @param macAlgorithm Mac algorithm to use, i.e. HMacSHA1 or HMacMD5.
 */
public MacBasedPRF(String macAlgorithm){
  this.macAlgorithm=macAlgorithm;
  try {
    mac=Mac.getInstance(macAlgorithm);
    hLen=mac.getMacLength();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 

Example 60

From project syslog4j, under directory /src/main/java/com/nesscomputing/syslog4j/impl/message/modifier/mac/.

Source file: MacSyslogMessageModifier.java

  19 
vote

public MacSyslogMessageModifier(MacSyslogMessageModifierConfig config) throws SyslogRuntimeException {
  super(config);
  this.config=config;
  try {
    this.mac=Mac.getInstance(config.getMacAlgorithm());
    this.mac.init(config.getKey());
  }
 catch (  NoSuchAlgorithmException nsae) {
    throw new SyslogRuntimeException(nsae);
  }
catch (  InvalidKeyException ike) {
    throw new SyslogRuntimeException(ike);
  }
}
 

Example 61

From project vysper, under directory /server/core/src/main/java/org/apache/vysper/xmpp/modules/extension/xep0220_server_dailback/.

Source file: DialbackIdGenerator.java

  19 
vote

public DialbackIdGenerator(){
  try {
    mac=Mac.getInstance("HmacSHA256");
    mac.init(signingKey);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeyException e) {
    throw new RuntimeException(e);
  }
}
 

Example 62

From project zk-service-registry-server, under directory /lib/zk-service-registry-server/zookeeper-3.3.3/contrib/bookkeeper/src/java/org/apache/bookkeeper/client/.

Source file: MacDigestManager.java

  19 
vote

public MacDigestManager(long ledgerId,byte[] passwd) throws GeneralSecurityException {
  super(ledgerId);
  byte[] macKey=genDigest("mac",passwd);
  SecretKeySpec keySpec=new SecretKeySpec(macKey,KEY_ALGORITHM);
  mac=Mac.getInstance(KEY_ALGORITHM);
  mac.init(keySpec);
}