コード例 #1
0
ファイル: WSTrustUtil.java プロジェクト: bdaw/picketlink
  /**
   * This method implements the {@code P_SHA-1} function as defined in the <i>RFC 2246 - The TLS
   * Protocol Version 1.0 Section 5. HMAC and the pseudorandom function</i>:
   *
   * <pre>
   * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
   *                        HMAC_hash(secret, A(2) + seed) +
   *                        HMAC_hash(secret, A(3) + seed) + ...
   *
   * Where + indicates concatenation.
   *
   * A() is defined as:
   *    A(0) = seed
   *    A(i) = HMAC_hash(secret, A(i-1))
   * </pre>
   *
   * @param secret a {@code byte[]} that represents the HMAC secret.
   * @param seed a {@code byte[]} that represents the seed to be used.
   * @param requiredSize an {@code int} that specifies the size (in bytes) of the result.
   * @return a {@code byte[]} containing the result of the {@code P_SHA-1} function.
   * @throws NoSuchAlgorithmException if an error occurs while creating the {@code Mac} instance.
   * @throws InvalidKeyException if an error occurs while initializing the {@code Mac} instance.
   */
  public static byte[] P_SHA1(byte[] secret, byte[] seed, int requiredSize)
      throws NoSuchAlgorithmException, InvalidKeyException {
    int offset = 0, copySize;
    byte[] result = new byte[requiredSize];
    byte[] A, partialResult;

    SecretKeySpec key = new SecretKeySpec(secret, "HMACSHA1");
    Mac mac = Mac.getInstance("HMACSHA1");

    // initialize A - A(0) = seed
    A = seed;
    while (requiredSize > 0) {
      // calculate the value of A()
      mac.init(key);
      mac.update(A);
      A = mac.doFinal();

      // now calculate HMAC_hash(secret, A + seed)
      mac.reset();
      mac.init(key);
      mac.update(A);
      mac.update(seed);
      partialResult = mac.doFinal();

      // copy the necessary bytes to the result.
      copySize = Math.min(requiredSize, partialResult.length);
      System.arraycopy(partialResult, 0, result, offset, copySize);
      offset += copySize;
      requiredSize -= copySize;
    }
    return result;
  }
コード例 #2
0
 @Override
 public void setUp() throws Exception {
   KEYBYTES1 = Base32String.decode("7777777777777777");
   KEYBYTES2 = Base32String.decode("22222222222222222");
   mac1 = Mac.getInstance("HMACSHA1");
   mac1.init(new SecretKeySpec(KEYBYTES1, ""));
   mac2 = Mac.getInstance("HMACSHA1");
   mac2.init(new SecretKeySpec(KEYBYTES2, ""));
   passcodeGenerator1 = new PasscodeGenerator(mac1);
   passcodeGenerator2 = new PasscodeGenerator(mac2);
   signer = AccountDb.getSigningOracle("7777777777777777");
 }
コード例 #3
0
ファイル: SoftHSM.java プロジェクト: BrunoDelb/openkeystore
  @Override
  public void generateAndVerifySessionKey(
      ECPublicKey client_ephemeral_key,
      byte[] kdf_data,
      byte[] attestation_arguments,
      X509Certificate device_certificate,
      byte[] session_attestation)
      throws IOException {
    try {
      // SP800-56A C(2, 0, ECC CDH)
      KeyAgreement key_agreement = KeyAgreement.getInstance("ECDH");
      key_agreement.init(server_ec_private_key);
      key_agreement.doPhase(client_ephemeral_key, true);
      byte[] Z = key_agreement.generateSecret();

      // The custom KDF
      Mac mac = Mac.getInstance(MACAlgorithms.HMAC_SHA256.getJCEName());
      mac.init(new SecretKeySpec(Z, "RAW"));
      session_key = mac.doFinal(kdf_data);

      if (device_certificate == null) {
        // Privacy enabled mode
        mac = Mac.getInstance(MACAlgorithms.HMAC_SHA256.getJCEName());
        mac.init(new SecretKeySpec(session_key, "RAW"));
        byte[] session_key_attest = mac.doFinal(attestation_arguments);

        // Verify that the session key signature is correct
        if (!ArrayUtil.compare(session_key_attest, session_attestation)) {
          throw new IOException("Verify attestation failed");
        }
      } else {
        // E2ES mode
        PublicKey device_public_key = device_certificate.getPublicKey();

        // Verify that attestation was signed by the device key
        if (!new SignatureWrapper(
                device_public_key instanceof RSAPublicKey
                    ? AsymSignatureAlgorithms.RSA_SHA256
                    : AsymSignatureAlgorithms.ECDSA_SHA256,
                device_public_key)
            .update(attestation_arguments)
            .verify(session_attestation)) {
          throw new IOException("Verify provisioning signature failed");
        }
      }
    } catch (GeneralSecurityException e) {
      throw new IOException(e);
    }
  }
コード例 #4
0
 static String getCheckCode(String secret) throws GeneralSecurityException, DecodingException {
   final byte[] keyBytes = Base32String.decode(secret);
   Mac mac = Mac.getInstance("HMACSHA1");
   mac.init(new SecretKeySpec(keyBytes, ""));
   PasscodeGenerator pcg = new PasscodeGenerator(mac);
   return pcg.generateResponseCode(0L);
 }
コード例 #5
0
  private int verify_code(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {
    byte[] data = new byte[8];
    long value = t;
    for (int i = 8; i-- > 0; value >>>= 8) {
      data[i] = (byte) value;
    }

    SecretKeySpec signKey = new SecretKeySpec(key, CRYPTO_ALGO);
    Mac mac = Mac.getInstance(CRYPTO_ALGO);
    mac.init(signKey);
    byte[] hash = mac.doFinal(data);

    int offset = hash[20 - 1] & 0xF;

    // We're using a long because Java hasn't got unsigned int.
    long truncatedHash = 0;
    for (int i = 0; i < 4; ++i) {
      truncatedHash <<= 8;
      // We are dealing with signed bytes:
      // we just keep the first byte.
      truncatedHash |= (hash[offset + i] & 0xFF);
    }

    truncatedHash &= 0x7FFF_FFFF;
    truncatedHash %= 1_000_000;

    return (int) truncatedHash;
  }
コード例 #6
0
ファイル: KBEncrypt.java プロジェクト: lovebomb/deepplin-base
  public void loadAllSilently(String filepath) {
    try {
      loadProperties(filepath);

      if (mCryptKeyNameAria256CBCPad != null && mCryptKeyNameAria256CBCPad.length() > 0)
        loadKeyFromDSMServer(mKBDMSURL, mCryptKeyNameAria256CBCPad, mCryptKeyARIA256);
      if (mCryptKeyNameAria128CBCPad != null && mCryptKeyNameAria128CBCPad.length() > 0)
        loadKeyFromDSMServer(mKBDMSURL, mCryptKeyNameAria128CBCPad, mCryptKeyARIA128CBCPAD);
      if (mCryptKeyNameSha256 != null && mCryptKeyNameSha256.length() > 0)
        loadKeyFromDSMServer(mKBDMSURL, mCryptKeyNameSha256, mCryptKeyHMACSHA256);
      if (mCryptKeyNameSeed128CBCPad != null && mCryptKeyNameSeed128CBCPad.length() > 0)
        loadKeyFromDSMServer(mKBDMSURL, mCryptKeyNameSeed128CBCPad, mCryptKeySEED128);
      if (mCryptKeyNameAria128CBCPadInternal != null
          && mCryptKeyNameAria128CBCPadInternal.length() > 0)
        loadKeyFromDSMServer(
            mKBDMSURL, mCryptKeyNameAria128CBCPadInternal, mCryptKeyARIA128CBCPADINTERNAL);

      //////////////////////// this code is for test.... !!!!!
      //			if ( mCryptKeyARIA256 == null ){
      //				mCryptKeyARIA256 = new byte[32];
      //				byte aria256key[] =
      // hexstrToBytes("1B0CA8CD900C026E92B5A883F515D65E9900E1884DFD4176F6716696AF2A834E".toLowerCase());
      //				System.arraycopy(aria256key, 0, mCryptKeyARIA256, 0, 32);
      //			}

      mSha256_Hmac = Mac.getInstance("HmacSHA256");
      SecretKeySpec secret_key = new SecretKeySpec(mCryptKeyHMACSHA256, "HmacSHA256");
      mSha256_Hmac.init(secret_key);

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #7
0
ファイル: AuthPolicy.java プロジェクト: wangjinlei/java-sdk
  public byte[] makeAuthToken() {

    byte[] accessKey = Config.getAccessKey().getBytes();
    byte[] secretKey = Config.getSecretKey().getBytes();
    try {
      String policyJson = this.marshal();
      byte[] policyBase64 = Client.urlsafeEncodeBytes(policyJson.getBytes());

      Mac mac = Mac.getInstance("HmacSHA1");
      SecretKeySpec keySpec = new SecretKeySpec(secretKey, "HmacSHA1");
      mac.init(keySpec);

      byte[] digest = mac.doFinal(policyBase64);
      byte[] digestBase64 = Client.urlsafeEncodeBytes(digest);
      byte[] token = new byte[accessKey.length + 30 + policyBase64.length];

      System.arraycopy(accessKey, 0, token, 0, accessKey.length);
      token[accessKey.length] = ':';
      System.arraycopy(digestBase64, 0, token, accessKey.length + 1, digestBase64.length);
      token[accessKey.length + 29] = ':';
      System.arraycopy(policyBase64, 0, token, accessKey.length + 30, policyBase64.length);

      return token;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return null;
  }
コード例 #8
0
  @Override
  protected void service(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    String policy_document = IoUtil.readStream(req.getInputStream());
    System.out.println(policy_document);
    String policy =
        BaseEncoding.base64()
            .encode(policy_document.getBytes("UTF-8"))
            .replaceAll("\n", "")
            .replaceAll("\r", "");

    Mac hmac;
    try {
      hmac = Mac.getInstance("HmacSHA1");
      String aws_secret_key = req.getParameter("aws-secret-key");
      System.out.println(aws_secret_key);

      hmac.init(new SecretKeySpec(aws_secret_key.getBytes("UTF-8"), "HmacSHA1"));
      String signature =
          BaseEncoding.base64().encode(hmac.doFinal(policy.getBytes("UTF-8"))).replaceAll("\n", "");
      res.setStatus(HttpServletResponse.SC_OK);
      res.setContentType("application/json");
      res.getWriter().write("{\"signature\":\"" + signature + "\",\"policy\":\"" + policy + "\"}");
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
      throw new RuntimeException(e);
    }
  }
コード例 #9
0
ファイル: Crypto.java プロジェクト: imbo/imboclient-java
  /**
   * Hash a string of data using a given key with the HMAC-SHA256 algorithm
   *
   * @param data Input data
   * @param key Key to use for hashing
   * @return Hashed output
   */
  public static String hashHmacSha256(String data, String key) {
    Charset charset = Charset.forName("UTF-8");
    String algoName = "HmacSHA256";
    Mac algorithm = null;
    try {
      algorithm = Mac.getInstance(algoName);
    } catch (NoSuchAlgorithmException e) {
      // This should hopefully never happen
      return "hmac-sha-256-algorithm-not-found";
    }

    byte[] byteKey = charset.encode(key).array();
    SecretKeySpec secretKey = new javax.crypto.spec.SecretKeySpec(byteKey, algoName);
    try {
      algorithm.init(secretKey);
    } catch (InvalidKeyException e) {
      // .. And this shouldn't really ever happen, either
      return "invalid-key-for-access-token-generation";
    }

    final byte[] macData = algorithm.doFinal(data.getBytes());

    String result = "";
    for (final byte element : macData) {
      result += Integer.toString((element & 0xff) + 0x100, 16).substring(1);
    }

    return result;
  }
コード例 #10
0
  private String generateRandomMACHash(int algorithm) throws Exception {
    // Generates a secret key
    SecretKey sk = null;
    switch (algorithm) {
      case RandomValueMeta.TYPE_RANDOM_MAC_HMACMD5:
        sk = data.keyGenHmacMD5.generateKey();
        break;
      case RandomValueMeta.TYPE_RANDOM_MAC_HMACSHA1:
        sk = data.keyGenHmacSHA1.generateKey();
        break;
      default:
        break;
    }

    if (sk == null) {
      throw new KettleException(BaseMessages.getString(PKG, "RandomValue.Log.SecretKeyNull"));
    }

    // Create a MAC object using HMAC and initialize with key
    Mac mac = Mac.getInstance(sk.getAlgorithm());
    mac.init(sk);
    // digest
    byte[] hashCode = mac.doFinal();
    StringBuilder encoded = new StringBuilder();
    for (int i = 0; i < hashCode.length; i++) {
      String _b = Integer.toHexString(hashCode[i]);
      if (_b.length() == 1) {
        _b = "0" + _b;
      }
      encoded.append(_b.substring(_b.length() - 2));
    }

    return encoded.toString();
  }
コード例 #11
0
    public ImportImageBuilder withBucketUploadPolicy(final String bucket, final String prefix) {
      try {
        final AccessKey adminAccessKey = Accounts.lookupSystemAdmin().getKeys().get(0);
        this.importDisk.setAccessKey(adminAccessKey.getAccessKey());
        final Calendar c = Calendar.getInstance();
        c.add(Calendar.HOUR, 48); // IMPORT_TASK_EXPIRATION_HOURS=48
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        final String expiration = sdf.format(c.getTime());
        // based on
        // http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-BundleInstance.html
        final String policy =
            String.format(
                "{\"expiration\":\"%s\",\"conditions\":[{\"bucket\": \"%s\"},"
                    + "[\"starts-with\", \"$key\", \"%s\"],{\"acl\":\"aws-exec-read\"}]}",
                expiration, bucket, prefix);
        this.importDisk.setUploadPolicy(B64.standard.encString(policy));

        final Mac hmac = Mac.getInstance("HmacSHA1");
        hmac.init(new SecretKeySpec(adminAccessKey.getSecretKey().getBytes("UTF-8"), "HmacSHA1"));

        this.importDisk.setUploadPolicySignature(
            B64.standard.encString(hmac.doFinal(B64.standard.encString(policy).getBytes("UTF-8"))));
      } catch (final Exception ex) {
        throw Exceptions.toUndeclared(ex);
      }
      return this;
    }
コード例 #12
0
ファイル: Crypto.java プロジェクト: eclettica/play1
  /**
   * Sign a message with a key
   *
   * @param message The message to sign
   * @param key The key to use
   * @return The signed message (in hexadecimal)
   */
  public static String sign(String message, byte[] key) {

    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 UnexpectedException(ex);
    }
  }
コード例 #13
0
ファイル: MAC.java プロジェクト: MondayIsSun/J2SE
  public static void jdkHMacMD5() {
    KeyGenerator keyGenerator;
    try {
      // 生成密钥
      // keyGenerator = KeyGenerator.getInstance("HmacMD5");
      // SecretKey secretKey = keyGenerator.generateKey();
      // byte[] key = secretKey.getEncoded();
      byte[] key = Hex.decodeHex(new char[] {'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'});

      // 还原密钥
      SecretKey restoreSecretKey = new SecretKeySpec(key, "HmacMD5");

      // 实例和初始化Mac
      Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm());
      mac.init(restoreSecretKey);

      // 执行摘要
      byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());
      System.out.println("jdk hmacMD5:" + Hex.encodeHexString(hmacMD5Bytes));

    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (DecoderException e) {
      e.printStackTrace();
    }
  }
コード例 #14
0
ファイル: OAuth.java プロジェクト: arden/qweibo
  /**
   * Generates a signature using the HMAC-SHA1 algorithm
   *
   * @param url The full url that needs to be signed including its non OAuth url parameters
   * @param consumerSecret The consumer seceret
   * @param tokenSecret The token secret, if available. If not available pass null or an empty
   *     string
   * @param httpMethod The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)
   * @param parameters
   * @param normalizedUrl
   * @param normalizedRequestParameters
   * @return A base64 string of the hash value
   */
  private String generateSignature(
      URL url,
      String consumerSecret,
      String tokenSecret,
      String httpMethod,
      List<QParameter> parameters,
      StringBuffer normalizedUrl,
      StringBuffer normalizedRequestParameters) {

    String signatureBase =
        generateSignatureBase(
            url, httpMethod, parameters, normalizedUrl, normalizedRequestParameters);
    byte[] oauthSignature = null;
    try {
      Mac mac = Mac.getInstance(HMACSHA1SignatureType);
      String oauthKey =
          encode(consumerSecret)
              + "&"
              + ((tokenSecret == null || tokenSecret.equals("")) ? "" : encode(tokenSecret));
      SecretKeySpec spec = new SecretKeySpec(oauthKey.getBytes("US-ASCII"), HMACSHA1SignatureType);
      mac.init(spec);
      oauthSignature = mac.doFinal(signatureBase.getBytes("US-ASCII"));
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    return Base64Encoder.encode(oauthSignature);
  }
コード例 #15
0
 public static void main(String[] args) throws Exception {
   //
   // check args and get plaintext
   if (args.length != 1) {
     System.err.println("Usage: java MessageAuthenticationCodeExample text");
     System.exit(1);
   }
   byte[] plainText = args[0].getBytes("UTF8");
   //
   // get a key for the HmacMD5 algorithm
   System.out.println("\nStart generating key");
   KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
   SecretKey MD5key = keyGen.generateKey();
   System.out.println("Finish generating key");
   //
   // get a MAC object and update it with the plaintext
   Mac mac = Mac.getInstance("HmacMD5");
   mac.init(MD5key);
   mac.update(plainText);
   //
   // print out the provider used and the MAC
   System.out.println("\n" + mac.getProvider().getInfo());
   System.out.println("\nMAC: ");
   System.out.println(new String(mac.doFinal(), "UTF8"));
 }
コード例 #16
0
  /**
   * Generates encoded URL params for EB SSO url. It uses current timestamp. Generated link can be
   * useful within 60 seconds.
   *
   * @param userId user name(aka sAMAccountName from ldap) of the user.
   * @return encoded URL params for EB SSO URL
   * @throws CannotGenerateEBSSOURLParams if there were some errors while encoding. Generally it
   *     means that there are arrors in algorithm code
   */
  public static String generateEBSSOURLParams(String userId) {
    try {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

      String timeStamp = sdf.format(new Date());

      StringBuilder messageString = new StringBuilder(100);

      messageString.append(USERNAME);
      messageString.append(userId);
      messageString.append(TIMESTAMP);
      messageString.append(timeStamp);
      messageString.append(END);

      Cipher cipher = null;

      cipher = Cipher.getInstance(CIPHER_TYPE);

      byte[] seed = SecureRandom.getSeed(16);

      IvParameterSpec ips = new IvParameterSpec(seed);

      cipher.init(
          Cipher.ENCRYPT_MODE, new SecretKeySpec(KEY.getBytes(ENCODING), CIPHER_TYPE_LESS), ips);

      byte[] cryptedData = cipher.doFinal(messageString.toString().getBytes(ENCODING));

      Mac hmac = Mac.getInstance(HMAC_TYPE);
      hmac.init(new SecretKeySpec(HMAC_KEY.getBytes(ENCODING), EMPTY_STRING));

      byte[] sigCheck = hmac.doFinal(cryptedData);

      String encodedSignature =
          new BASE64Encoder().encode(sigCheck).replaceAll("\n", "").replaceAll("\r", "");

      String encodedSeed =
          new BASE64Encoder().encode(seed).replaceAll("\n", "").replaceAll("\r", "");

      String encodedCryptedData =
          new BASE64Encoder().encode(cryptedData).replaceAll("\n", "").replaceAll("\r", "");

      StringBuilder params = new StringBuilder(220);

      params.append(encodedSignature);
      params.append(SEMI_COLON);
      params.append(encodedSeed);
      params.append(SEMI_COLON);
      params.append(encodedCryptedData);

      return URLEncoder.encode(params.toString(), ENCODING);
    } catch (Throwable e) {
      System.out.println(
          "Ups. Something wrong with generateEBSSOURLParams: userid: '"
              + userId
              + "': "
              + e.getMessage());
      e.printStackTrace();
      return "";
    }
  }
コード例 #17
0
 /**
  * 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>
  */
 /*package*/ 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 {
       spec = token.getSecretKeySpec();
       if (null == spec) {
         String oauthSignature = encode(consumerSecret) + "&" + encode(token.getTokenSecret());
         spec = new SecretKeySpec(oauthSignature.getBytes(), HMAC_SHA1);
         token.setSecretKeySpec(spec);
       }
     }
     mac.init(spec);
     byteHMAC = mac.doFinal(data.getBytes());
   } catch (InvalidKeyException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException ignore) {
     // should never happen
   }
   return BASE64Encoder.encode(byteHMAC);
 }
コード例 #18
0
  // Validates HMAC-SHA1 signatures included in webhook notifications
  // to ensure notifications came from Square
  public static boolean isValidCallback(String callbackBody, String callbackSignature) {

    // Combine your webhook notification URL and the JSON body of the incoming request into a single
    // string
    String stringToSign = _webhookUrl + callbackBody;

    String result;

    // Generate the HMAC-SHA1 signature of the string, signed with your webhook signature key
    try {
      SecretKeySpec signingKey = new SecretKeySpec(_webhookSignatureKey.getBytes(), "HmacSHA1");
      Mac mac = Mac.getInstance("HmacSHA1");
      mac.init(signingKey);
      byte[] rawHmac = mac.doFinal(stringToSign.getBytes());
      result = Base64.encodeBase64String(rawHmac);
    } catch (Exception e) {
      return false;
    }

    // Hash the two signatures a second time (to protect against timing attacks) and compare them
    try {
      MessageDigest digest = MessageDigest.getInstance("SHA-1");
      String hashedCallbackSignature = new String(digest.digest(callbackSignature.getBytes()));
      String hashedResult = new String(digest.digest(result.getBytes()));

      return hashedCallbackSignature.equals(hashedResult);
    } catch (NoSuchAlgorithmException e) {
      return false;
    }
  }
コード例 #19
0
ファイル: Oauth.java プロジェクト: zjgithub2012/weibo4j
  /*
   * 解析站内应用post的SignedRequest split为part1和part2两部分
   */
  public String parseSignedRequest(String signed_request)
      throws IOException, InvalidKeyException, NoSuchAlgorithmException {
    String[] t = signed_request.split("\\.", 2);
    // 为了和 url encode/decode 不冲突,base64url 编码方式会将
    // '+','/'转换成'-','_',并且去掉结尾的'='。 因此解码之前需要还原到默认的base64编码,结尾的'='可以用以下算法还原
    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;
    }
  }
コード例 #20
0
 /**
  * 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>
  */
 /* package */ String generateSignature(final String data, final OAuthToken token) {
   byte[] byteHMAC = null;
   try {
     final Mac mac = Mac.getInstance(HMAC_SHA1);
     SecretKeySpec spec;
     if (null == token) {
       final String oauthSignature = HttpParameter.encode(consumerSecret) + "&";
       spec = new SecretKeySpec(oauthSignature.getBytes(), HMAC_SHA1);
     } else {
       spec = token.getSecretKeySpec();
       if (null == spec) {
         final 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 (final InvalidKeyException ike) {
     logger.error("Failed initialize \"Message Authentication Code\" (MAC)", ike);
     throw new AssertionError(ike);
   } catch (final NoSuchAlgorithmException nsae) {
     logger.error("Failed to get HmacSHA1 \"Message Authentication Code\" (MAC)", nsae);
     throw new AssertionError(nsae);
   }
   return BASE64Encoder.encode(byteHMAC);
 }
コード例 #21
0
 public void init(byte[] P) {
   try {
     mac.init(new SecretKeySpec(P, macAlgorithm));
   } catch (InvalidKeyException e) {
     throw new RuntimeException(e);
   }
 }
コード例 #22
0
ファイル: MTurk.java プロジェクト: bmyerz/turkit
  /** Computes a Signature for use in MTurk REST requests. */
  public static String getSignature(
      String service, String operation, String timestamp, String secretKey) throws Exception {

    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(new SecretKeySpec(secretKey.getBytes(), HMAC_SHA1_ALGORITHM));
    return Base64.encodeBytes(mac.doFinal((service + operation + timestamp).getBytes()));
  }
コード例 #23
0
  private String query(String method, HashMap<String, String> args) {
    Mac mac = null;
    SecretKeySpec key = null;
    args.put("method", method);
    long time = System.currentTimeMillis() / 1000L;
    args.put("nonce", "" + (int) (time));
    String postData = "";
    for (Iterator argumentIterator = args.entrySet().iterator(); argumentIterator.hasNext(); ) {
      Map.Entry argument = (Map.Entry) argumentIterator.next();

      if (postData.length() > 0) {
        postData += "&";
      }
      postData += argument.getKey() + "=" + argument.getValue();
    }
    try {
      key = new SecretKeySpec(apisecret.getBytes("UTF-8"), "HmacSHA512");
      mac = Mac.getInstance("HmacSHA512");
      mac.init(key);
      URL queryUrl = new URL("https://btc-e.com/tapi/");
      HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();
      connection.setDoOutput(true);
      connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; Java Test client)");
      connection.setRequestProperty("Key", apikey);
      connection.setRequestProperty(
          "Sign", Hex.encodeHexString(mac.doFinal(postData.getBytes("UTF-8"))));
      connection.getOutputStream().write(postData.getBytes());
      StringWriter writer = new StringWriter();
      IOUtils.copy(connection.getInputStream(), writer, "UTF-8");
      return writer.toString();
    } catch (Exception ex) {
      utils.logger.log(true, ex.getMessage());
    }
    return new String();
  }
コード例 #24
0
ファイル: Mac.java プロジェクト: dyglcc/mmwd
  /**
   * makes a upload token.
   *
   * @param data
   * @return
   * @throws AuthException
   */
  public String signWithData(byte[] data) throws AuthException {
    byte[] accessKey = this.accessKey.getBytes();
    byte[] secretKey = this.secretKey.getBytes();

    try {
      byte[] policyBase64 = EncodeUtils.urlsafeEncodeBytes(data);

      javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
      SecretKeySpec keySpec = new SecretKeySpec(secretKey, "HmacSHA1");
      mac.init(keySpec);

      byte[] digest = mac.doFinal(policyBase64);
      byte[] digestBase64 = EncodeUtils.urlsafeEncodeBytes(digest);
      byte[] token = new byte[accessKey.length + 30 + policyBase64.length];

      System.arraycopy(accessKey, 0, token, 0, accessKey.length);
      token[accessKey.length] = ':';
      System.arraycopy(digestBase64, 0, token, accessKey.length + 1, digestBase64.length);
      token[accessKey.length + 29] = ':';
      System.arraycopy(policyBase64, 0, token, accessKey.length + 30, policyBase64.length);

      return new String(token);
    } catch (Exception e) {
      throw new AuthException("Fail to sign with data!", e);
    }
  }
コード例 #25
0
ファイル: TlsHelper.java プロジェクト: pvillard31/nifi
 public static byte[] calculateHMac(String token, PublicKey publicKey)
     throws GeneralSecurityException {
   SecretKeySpec keySpec = new SecretKeySpec(token.getBytes(StandardCharsets.UTF_8), "RAW");
   Mac mac = Mac.getInstance("Hmac-SHA256", BouncyCastleProvider.PROVIDER_NAME);
   mac.init(keySpec);
   return mac.doFinal(getKeyIdentifier(publicKey));
 }
コード例 #26
0
ファイル: GOST28147Test.java プロジェクト: XShandow/bc-java
  public void performTest() throws Exception {
    for (int i = 0; i != cipherTests.length; i += 8) {
      testECB(
          Integer.parseInt(cipherTests[i]),
          Hex.decode(cipherTests[i + 1]),
          Hex.decode(cipherTests[i + 2]),
          Hex.decode(cipherTests[i + 3]));

      testCFB(
          Integer.parseInt(cipherTests[i + 4]),
          Hex.decode(cipherTests[i + 4 + 1]),
          Hex.decode(cipherTests[i + 4 + 2]),
          Hex.decode(cipherTests[i + 4 + 3]));

      oidTest();
    }

    Mac mac = Mac.getInstance("GOST28147MAC", "BC");

    mac.init(
        new SecretKeySpec(
            Hex.decode("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"),
            "GOST28147"));

    if (!Arrays.areEqual(
        Hex.decode("1b69996e"),
        mac.doFinal(Hex.decode("4e6f77206973207468652074696d6520666f7220616c6c20")))) {
      fail("mac test falied.");
    }
  }
コード例 #27
0
ファイル: AESEncrypt.java プロジェクト: minthubk/TwangR
 /**
  * Generate the mac based on HMAC_ALGORITHM
  *
  * @param integrityKey The key used for hmac
  * @param byteCipherText the cipher text
  * @return A byte array of the HMAC for the given key & ciphertext
  * @throws NoSuchAlgorithmException
  * @throws InvalidKeyException
  */
 public static byte[] generateMac(byte[] byteCipherText, SecretKey integrityKey)
     throws NoSuchAlgorithmException, InvalidKeyException {
   // Now compute the mac for later integrity checking
   Mac sha256_HMAC = Mac.getInstance(HMAC_ALGORITHM);
   sha256_HMAC.init(integrityKey);
   return sha256_HMAC.doFinal(byteCipherText);
 }
コード例 #28
0
 private String createMac(Key secKey, String ciphertext) throws GeneralSecurityException {
   Mac mac = Mac.getInstance("HMACSHA256", PROVIDER_NAME);
   //    mac.init(new SecretKeySpec(Base64.encode(secKey.getEncoded()), "AES"));
   mac.init(secKey);
   byte[] hmacBytes = mac.doFinal(WeaveUtil.toAsciiBytes(ciphertext));
   return WeaveUtil.toAsciiString(Hex.encode(hmacBytes));
 }
コード例 #29
0
 /**
  * This method: Encrypts bytes using a cipher. Generates MAC for intialization vector of the
  * cipher Generates MAC for encrypted data Returns a byte array consisting of the following
  * concatenated together: |MAC for cnrypted Data | MAC for Init Vector | Encrypted Data |
  *
  * @param bytes The byte array to be encrypted.
  * @return the encrypted byte array.
  */
 public byte[] encrypt(byte[] bytes) {
   byte[] securedata = null;
   try {
     // Generate IV
     SecureRandom rand = new SecureRandom();
     byte[] iv = new byte[16];
     rand.nextBytes(iv);
     IvParameterSpec ivspec = new IvParameterSpec(iv);
     Cipher encryptCipher = Cipher.getInstance(CIPHER_CODE);
     encryptCipher.init(Cipher.ENCRYPT_MODE, sk, ivspec);
     Mac encryptMac = Mac.getInstance(MAC_CODE);
     encryptMac.init(sk);
     encryptMac.update(iv);
     // encrypt the plaintext
     byte[] encdata = encryptCipher.doFinal(bytes);
     byte[] macBytes = encryptMac.doFinal(encdata);
     byte[] tmp = concatBytes(macBytes, iv);
     securedata = concatBytes(tmp, encdata);
   } catch (NoSuchAlgorithmException
       | NoSuchPaddingException
       | InvalidKeyException
       | InvalidAlgorithmParameterException
       | IllegalStateException
       | IllegalBlockSizeException
       | BadPaddingException e) {
     if (LOGGER.isLoggable(Level.SEVERE)) {
       LOGGER.log(
           Level.SEVERE,
           "Unexpected exception initializing encryption." + "  No encryption will be performed.",
           e);
     }
     return null;
   }
   return securedata;
 }
コード例 #30
0
ファイル: Pusher.java プロジェクト: GuziJob/Wegas
  /**
   * Returns a HMAC/SHA256 representation of the given string
   *
   * @param data
   * @return
   */
  private static String hmacsha256Representation(String data) {
    try {
      // Create the HMAC/SHA256 key from application secret
      final SecretKeySpec signingKey =
          new SecretKeySpec(pusherApplicationSecret.getBytes(), "HmacSHA256");

      // Create the message authentication code (MAC)
      final Mac mac = Mac.getInstance("HmacSHA256");
      mac.init(signingKey);

      // Process and return data
      byte[] digest = mac.doFinal(data.getBytes("UTF-8"));
      digest = mac.doFinal(data.getBytes());
      // Convert to string
      BigInteger bigInteger = new BigInteger(1, digest);
      return String.format("%0" + (digest.length << 1) + "x", bigInteger);
    } catch (NoSuchAlgorithmException nsae) {
      // We should never come here, because GAE has HMac SHA256
      throw new RuntimeException("No HMac SHA256 algorithm");
    } catch (UnsupportedEncodingException e) {
      // We should never come here, because UTF-8 should be available
      throw new RuntimeException("No UTF-8");
    } catch (InvalidKeyException e) {
      throw new RuntimeException("Invalid key exception while converting to HMac SHA256");
    }
  }