Ejemplo n.º 1
0
  public static String getHmacSHA1(String data, String key) {
    byte[] ipadArray = new byte[64];
    byte[] opadArray = new byte[64];
    byte[] keyArray = new byte[64];
    int ex = key.length();
    SHA1 sha1 = new SHA1();
    if (key.length() > 64) {
      byte[] temp = sha1.getDigestOfBytes(key.getBytes());
      ex = temp.length;
      for (int i = 0; i < ex; i++) {
        keyArray[i] = temp[i];
      }
    } else {
      byte[] temp = key.getBytes();
      for (int i = 0; i < temp.length; i++) {
        keyArray[i] = temp[i];
      }
    }
    for (int i = ex; i < 64; i++) {
      keyArray[i] = 0;
    }
    for (int j = 0; j < 64; j++) {
      ipadArray[j] = (byte) (keyArray[j] ^ 0x36);
      opadArray[j] = (byte) (keyArray[j] ^ 0x5C);
    }
    byte[] tempResult = sha1.getDigestOfBytes(join(ipadArray, data.getBytes()));

    return sha1.getDigestOfString(join(opadArray, tempResult));
  }
Ejemplo n.º 2
0
 /**
  * To save from Attacks on Parameter Authentication one can send hash of parameters to other party
  *
  * @return byte[] of what???
  */
 @Override
 public byte[] getParametersHash() {
   byte[] parms = NativeLib.getECParameters(ecGroup);
   SHA1 sha1 = new SHA1(BLOCK_SIZE);
   sha1.update(parms, 0, parms.length);
   sha1.generate();
   byte[] digest = sha1.getDigest();
   return digest;
 }
Ejemplo n.º 3
0
 @Override
 public boolean checkParametersHash(byte[] hash) {
   if (hash == null || hash.length != BLOCK_SIZE) return false;
   byte[] parms = NativeLib.getECParameters(ecGroup);
   SHA1 sha1 = new SHA1(BLOCK_SIZE);
   sha1.update(parms, 0, parms.length);
   sha1.generate();
   byte[] digest = sha1.getDigest();
   for (int i = 0; i < digest.length; i++) if (digest[i] != hash[i]) return false;
   return true;
 }
  public static void main(String[] args) throws NoSuchAlgorithmException {
    int secretKeyLength = Integer.parseInt(args[0]);
    String originalMessage = args[1];
    String originalHash = args[2];
    String hackedSuffix = args[3];
    byte[] hackedSuffixBytes = hackedSuffix.getBytes();

    // The length of the message with the secret key
    int originalMessageLengthWithKey = secretKeyLength + originalMessage.length();

    // The length of the padding on the original message
    int originalMessagePaddingLength = generatePadding(originalMessageLengthWithKey).length;

    // The length of the message with the secret key and padding
    int totalOriginalMessageLength = originalMessageLengthWithKey + originalMessagePaddingLength;

    // The length of the hacked message
    int hackedMessageLength = totalOriginalMessageLength + hackedSuffix.length();

    // The padding for the hacked message
    byte[] hackedMessagePadding = generatePadding(hackedSuffixBytes.length, hackedMessageLength);

    // The hacked message with the hacked padding
    byte[] hackedMessageBytes = SHA1.concat(hackedSuffix.getBytes(), hackedMessagePadding);

    // Print out the new hash from the hacked message
    System.out.println(
        "New hash: " + encode(toShorts(hackedMessageBytes), extractState(originalHash), false));
  }
Ejemplo n.º 5
0
 void put(final URI uri, ArtifactData data) throws Exception {
   reporter.trace("put %s %s", uri, data);
   File tmp = createTempFile(repoDir, "mtp", ".whatever");
   tmp.deleteOnExit();
   try {
     copy(uri.toURL(), tmp);
     byte[] sha = SHA1.digest(tmp).digest();
     reporter.trace("SHA %s %s", uri, Hex.toHexString(sha));
     ArtifactData existing = get(sha);
     if (existing != null) {
       reporter.trace("existing");
       xcopy(existing, data);
       return;
     }
     File meta = new File(repoDir, Hex.toHexString(sha) + ".json");
     File file = new File(repoDir, Hex.toHexString(sha));
     rename(tmp, file);
     reporter.trace("file %s", file);
     data.file = file.getAbsolutePath();
     data.sha = sha;
     data.busy = false;
     CommandData cmddata = parseCommandData(data);
     if (cmddata.bsn != null) {
       data.name = cmddata.bsn + "-" + cmddata.version;
     } else data.name = Strings.display(cmddata.title, cmddata.bsn, cmddata.name, uri);
     codec.enc().to(meta).put(data);
     reporter.trace("TD = " + data);
   } finally {
     tmp.delete();
     reporter.trace("puted %s %s", uri, data);
   }
 }
Ejemplo n.º 6
0
 /** @throws UnsupportedOperationException if not supported */
 public MessageDigest getDigestInstance() {
   if (digestName.equals("SHA-1")) return SHA1.getInstance();
   if (digestName.equals("SHA-256")) return SHA256Generator.getDigestInstance();
   try {
     return MessageDigest.getInstance(digestName);
   } catch (NoSuchAlgorithmException e) {
     throw new UnsupportedOperationException(e);
   }
 }
Ejemplo n.º 7
0
  /**
   * Runs an integrity test.
   *
   * @return true: selftest passed / false: selftest failed
   */
  public boolean selfTest() {
    int nI;
    SHA1 tester;
    byte[] digest;

    tester = new SHA1();

    tester.update(SELFTEST_MESSAGE);
    tester.finalize();

    digest = tester.getDigest();

    for (nI = 0; nI < DIGEST_SIZE; nI++) {
      if (digest[nI] != SELFTEST_DIGEST[nI]) {
        return false;
      }
    }
    return true;
  }
Ejemplo n.º 8
0
 /**
  * 检验消息的真实性,并且获取解密后的明文.
  *
  * <ol>
  *   <li>利用收到的密文生成安全签名,进行签名验证
  *   <li>若验证通过,则提取xml中的加密消息
  *   <li>对消息进行解密
  * </ol>
  *
  * @param msgSignature 签名串,对应URL参数的msg_signature
  * @param timeStamp 时间戳,对应URL参数的timestamp
  * @param nonce 随机串,对应URL参数的nonce
  * @param encrypt 密文,对应POST请求的数据
  * @return 解密后的原文
  * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
  */
 public String decryptMsg(String msgSignature, String timeStamp, String nonce, String encrypt)
     throws AesException {
   // 验证安全签名
   String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt);
   if (!signature.equals(msgSignature)) {
     throw new AesException(AesException.ValidateSignatureError);
   }
   // 解密
   LOG.info("wx:signature success,to decrypt encryptMsg is ", encrypt);
   return decrypt(encrypt);
 }
Ejemplo n.º 9
0
  /**
   * 验证URL
   *
   * @param msgSignature 签名串,对应URL参数的msg_signature
   * @param timeStamp 时间戳,对应URL参数的timestamp
   * @param nonce 随机串,对应URL参数的nonce
   * @param echoStr 随机串,对应URL参数的echostr
   * @return 解密之后的echostr
   * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
   */
  public String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr)
      throws AesException {
    String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr);

    if (!signature.equals(msgSignature)) {
      throw new AesException(AesException.ValidateSignatureError);
    }

    String result = decrypt(echoStr);
    return result;
  }
Ejemplo n.º 10
0
  /**
   * 将公众平台回复用户的消息加密打包.
   *
   * <ol>
   *   <li>对要发送的消息进行AES-CBC加密
   *   <li>生成安全签名
   *   <li>将消息密文和安全签名打包成xml格式
   * </ol>
   *
   * @param replyMsg 公众平台待回复用户的消息,xml格式的字符串 // * @param timeStamp 时间戳,可以自己生成,也可以用URL参数的timestamp //
   *     * @param nonce 随机串,可以自己生成,也可以用URL参数的nonce // *
   * @return 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串
   * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
   */
  public String encryptMsg(String replyMsg) throws AesException, IOException {
    // 加密
    String encrypt = encrypt(getRandomStr(), replyMsg);

    // 生成安全签名
    String timeStamp = Long.toString(System.currentTimeMillis());
    String nonce = getRandomStr();
    String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt);
    // 生成发送的xml
    String result = WXXMLParse.getReplyMsgXML(encrypt, signature, timeStamp, nonce);
    return result;
  }
Ejemplo n.º 11
0
 /**
  * Reads the stream until EOF. Does not close the stream.
  *
  * @return hash SHA-1 hash, NOT a SHA-256 hash
  */
 public SHA1Hash calculateHash(InputStream in) {
   MessageDigest digest = SHA1.getInstance();
   byte buf[] = new byte[64];
   int read = 0;
   try {
     while ((read = in.read(buf)) != -1) {
       digest.update(buf, 0, read);
     }
   } catch (IOException ioe) {
     if (_log.shouldLog(Log.WARN)) _log.warn("Unable to hash the stream", ioe);
     return null;
   }
   return new SHA1Hash(digest.digest());
 }
Ejemplo n.º 12
0
  /**
   * 将公众平台回复用户的消息加密打包.
   *
   * <ol>
   *   <li>对要发送的消息进行AES-CBC加密
   *   <li>生成安全签名
   *   <li>将消息密文和安全签名打包成xml格式
   * </ol>
   *
   * @param replyMsg 公众平台待回复用户的消息,xml格式的字符串
   * @param timeStamp 时间戳,可以自己生成,也可以用URL参数的timestamp
   * @param nonce 随机串,可以自己生成,也可以用URL参数的nonce
   * @return 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串
   * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
   */
  public String encryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException {
    // 加密
    String encrypt = encrypt(getRandomStr(), replyMsg);

    // 生成安全签名
    if (timeStamp == "") {
      timeStamp = Long.toString(System.currentTimeMillis());
    }

    String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt);

    // System.out.println("发送给平台的签名是: " + signature[1].toString());
    // 生成发送的xml
    String result = XMLParse.generate(encrypt, signature, timeStamp, nonce);
    return result;
  }
Ejemplo n.º 13
0
  public static void main(String[] args) {
    SHA1 sha = new SHA1();

    byte[] dig1 = new byte[20];
    byte[] dig2 = new byte[20];
    byte[] dig3 = new byte[20];

    /*
     * We do not specify a charset name for getBytes(), since we assume that
     * the JVM's default encoder maps the _used_ ASCII characters exactly as
     * getBytes("US-ASCII") would do. (Ah, yes, too lazy to catch the
     * exception that can be thrown by getBytes("US-ASCII")). Note: This has
     * no effect on the SHA-1 implementation, this is just for the following
     * test code.
     */

    sha.update("abc".getBytes());
    sha.digest(dig1);

    sha.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".getBytes());
    sha.digest(dig2);

    for (int i = 0; i < 1000000; i++) sha.update((byte) 'a');
    sha.digest(dig3);

    String dig1_res = toHexString(dig1);
    String dig2_res = toHexString(dig2);
    String dig3_res = toHexString(dig3);

    String dig1_ref = "A9993E364706816ABA3E25717850C26C9CD0D89D";
    String dig2_ref = "84983E441C3BD26EBAAE4AA1F95129E5E54670F1";
    String dig3_ref = "34AA973CD4C4DAA4F61EEB2BDBAD27316534016F";

    if (dig1_res.equals(dig1_ref)) System.out.println("SHA-1 Test 1 OK.");
    else System.out.println("SHA-1 Test 1 FAILED.");

    if (dig2_res.equals(dig2_ref)) System.out.println("SHA-1 Test 2 OK.");
    else System.out.println("SHA-1 Test 2 FAILED.");

    if (dig3_res.equals(dig3_ref)) System.out.println("SHA-1 Test 3 OK.");
    else System.out.println("SHA-1 Test 3 FAILED.");

    if (dig3_res.equals(dig3_ref)) System.out.println("SHA-1 Test 3 OK.");
    else System.out.println("SHA-1 Test 3 FAILED.");
  }
Ejemplo n.º 14
0
  /**
   * 检验消息的真实性,并且获取解密后的明文.
   *
   * <ol>
   *   <li>利用收到的密文生成安全签名,进行签名验证
   *   <li>若验证通过,则提取xml中的加密消息
   *   <li>对消息进行解密
   * </ol>
   *
   * @param msgSignature 签名串,对应URL参数的msg_signature
   * @param timeStamp 时间戳,对应URL参数的timestamp
   * @param nonce 随机串,对应URL参数的nonce
   * @param postData 密文,对应POST请求的数据
   * @return 解密后的原文
   * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
   */
  public String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData)
      throws AesException {

    // 密钥,公众账号的app secret
    // 提取密文
    Object[] encrypt = XMLParse.extract(postData);

    // 验证安全签名
    String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt[1].toString());

    // 和URL中的签名比较是否相等
    // System.out.println("第三方收到URL中的签名:" + msg_sign);
    // System.out.println("第三方校验签名:" + signature);
    if (!signature.equals(msgSignature)) {
      throw new AesException(AesException.ValidateSignatureError);
    }

    // 解密
    String result = decrypt(encrypt[1].toString());
    return result;
  }
Ejemplo n.º 15
0
 @Provides
 @Singleton
 SHA1 provideSHA1() {
   return SHA1.getInstance();
 }
Ejemplo n.º 16
0
  public String what(String key, boolean oneliner) throws Exception {
    byte[] sha;

    Matcher m = SHA_P.matcher(key);
    if (m.matches()) {
      sha = Hex.toByteArray(key);
    } else {
      m = URL_P.matcher(key);
      if (m.matches()) {
        URL url = new URL(key);
        sha = SHA1.digest(url.openStream()).digest();
      } else {
        File jarfile = new File(key);
        if (!jarfile.exists()) {
          reporter.error("File does not exist: %s", jarfile.getCanonicalPath());
        }
        sha = SHA1.digest(jarfile).digest();
      }
    }
    reporter.trace("sha %s", Hex.toHexString(sha));
    Revision revision = library.getRevision(sha);
    if (revision == null) {
      return null;
    }

    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    Justif justif = new Justif(120, 20, 70, 20, 75);
    DateFormat dateFormat = DateFormat.getDateInstance();

    try {
      if (oneliner) {
        f.format("%20s %s%n", Hex.toHexString(revision._id), createCoord(revision));
      } else {
        f.format("Artifact: %s%n", revision.artifactId);
        if (revision.organization != null && revision.organization.name != null) {
          f.format(" (%s)", revision.organization.name);
        }
        f.format("%n");
        f.format("Coordinates\t0: %s%n", createCoord(revision));
        f.format("Created\t0: %s%n", dateFormat.format(new Date(revision.created)));
        f.format("Size\t0: %d%n", revision.size);
        f.format("Sha\t0: %s%n", Hex.toHexString(revision._id));
        f.format("URL\t0: %s%n", createJpmLink(revision));
        f.format("%n");
        f.format("%s%n", revision.description);
        f.format("%n");
        f.format("Dependencies\t0:%n");
        boolean flag = false;
        Iterable<RevisionRef> closure = library.getClosure(revision._id, true);
        for (RevisionRef dep : closure) {
          f.format(
              " - %s \t2- %s \t3- %s%n",
              dep.name, createCoord(dep), dateFormat.format(new Date(dep.created)));
          flag = true;
        }
        if (!flag) {
          f.format("     None%n");
        }
        f.format("%n");
      }
      f.flush();
      justif.wrap(sb);
      return sb.toString();
    } finally {
      f.close();
    }
  }
Ejemplo n.º 17
0
 /** @return hash SHA-1 hash, NOT a SHA-256 hash */
 public static SHA1Hash calculateHash(byte[] source, int offset, int len) {
   MessageDigest h = SHA1.getInstance();
   h.update(source, offset, len);
   byte digested[] = h.digest();
   return new SHA1Hash(digested);
 }
  /** Load application settings from persistent store. */
  public void load() {
    Preferences preferences = getUnderlyingPreferences();

    // Authority certificates
    useCaCertificates = preferences.getBoolean(KSE3_USECACERTS, false);
    String cacertsPath =
        preferences.get(
            KSE3_CACERTSFILE, AuthorityCertificates.getDefaultCaCertificatesLocation().toString());
    caCertificatesFile = cleanFilePath(new File(cacertsPath));
    useWindowsTrustedRootCertificates = preferences.getBoolean(KSE3_USEWINTRUSTROOTCERTS, false);

    // Trust checks
    enableImportTrustedCertTrustCheck =
        preferences.getBoolean(KSE3_ENABLEIMPORTTRUSTEDCERTTRUSTCHECK, false);
    enableImportCaReplyTrustCheck =
        preferences.getBoolean(KSE3_ENABLEIMPORTCAREPLYTRUSTCHECK, false);

    // Key pair generation
    generateKeyPairType = KeyPairType.resolveJce(preferences.get(KSE3_KEYPAIRTYPE, RSA.jce()));
    if (generateKeyPairType == null) {
      generateKeyPairType = RSA;
    }
    int defaultKeyPairSize;
    if (generateKeyPairType == RSA) {
      defaultKeyPairSize = 2048;
    } else {
      defaultKeyPairSize = 1024; // DSA
    }
    generateKeyPairSize = preferences.getInt(KSE3_KEYPAIRSIZE, defaultKeyPairSize);

    // Secret key generation
    generateSecretKeyType = SecretKeyType.resolveJce(preferences.get(KSE3_SECKEYTYPE, AES.jce()));
    if (generateSecretKeyType == null) {
      generateSecretKeyType = AES;
    }
    generateSecretKeySize = preferences.getInt(KSE3_SECKEYSIZE, 192);

    // Certificate fingerprint
    certificateFingerprintType =
        DigestType.resolveJce(preferences.get(KSE3_CERTFINGERTYPE, SHA1.jce()));
    if (certificateFingerprintType == null) {
      certificateFingerprintType = SHA1;
    }

    // Password quality
    passwordQualityConfig =
        new PasswordQualityConfig(
            preferences.getBoolean(KSE3_PWDQUALENABLE, false),
            preferences.getBoolean(KSE3_MINPWDQUALENFORCE, false),
            preferences.getInt(KSE3_MINPWDQUAL, 60));

    // Internet proxy settings
    ProxyConfigurationType proxyConfigurationType =
        ProxyConfigurationType.resolve(
            preferences.get(KSE3_PROXY, ProxyConfigurationType.SYSTEM.name()));

    // default should be system settings because of "java.net.useSystemProxies=true", save it for
    // later usage
    SystemProxySelector.setSystemProxySelector(ProxySelector.getDefault());

    switch (proxyConfigurationType) {
      case NONE:
        ProxySelector.setDefault(new NoProxySelector());
        break;
      case PAC:
        // Use PAC URL for proxy configuration
        String pacUrl = preferences.get(KSE3_PACURL, null);
        if (pacUrl != null) {
          ProxySelector.setDefault(new PacProxySelector(pacUrl));
        } else {
          ProxySelector.setDefault(new NoProxySelector());
        }
        break;
      case MANUAL:
        // Use manual settings for HTTP, HTTPS and SOCKS
        ProxyAddress httpProxyAddress = null;
        ProxyAddress httpsProxyAddress = null;
        ProxyAddress socksProxyAddress = null;

        String httpHost = preferences.get(KSE3_HTTPHOST, null);
        int httpPort = preferences.getInt(KSE3_HTTPPORT, 0);

        if (httpHost != null && httpPort > 0) {
          httpProxyAddress = new ProxyAddress(httpHost, httpPort);
        }

        String httpsHost = preferences.get(KSE3_HTTPSHOST, null);
        int httpsPort = preferences.getInt(KSE3_HTTPSPORT, 0);

        if (httpsHost != null && httpsPort > 0) {
          httpsProxyAddress = new ProxyAddress(httpsHost, httpsPort);
        }

        String socksHost = preferences.get(KSE3_SOCKSHOST, null);
        int socksPort = preferences.getInt(KSE3_SOCKSPORT, 0);

        if (socksHost != null && socksPort > 0) {
          socksProxyAddress = new ProxyAddress(socksHost, socksPort);
        }

        if (httpProxyAddress != null || httpsProxyAddress != null) {
          ProxySelector.setDefault(
              new ManualProxySelector(
                  httpProxyAddress, httpsProxyAddress, null, socksProxyAddress));
        } else {
          // no manual settings - use no proxy to connect to the Internet
          ProxySelector.setDefault(new NoProxySelector());
        }
        break;
      case SYSTEM:
      default:
        ProxySelector.setDefault(new SystemProxySelector());
        break;
    }

    // Application size and position
    sizeAndPosition =
        new Rectangle(
            preferences.getInt(KSE3_XPOS, 0),
            preferences.getInt(KSE3_YPOS, 0),
            preferences.getInt(KSE3_WIDTH, KseFrame.DEFAULT_WIDTH),
            preferences.getInt(KSE3_HEIGHT, KseFrame.DEFAULT_HEIGHT));

    // User interface
    showToolBar = preferences.getBoolean(KSE3_SHOWTOOLBAR, true);
    showStatusBar = preferences.getBoolean(KSE3_SHOWSTATUSBAR, true);
    tabLayout = preferences.getInt(KSE3_TABLAYOUT, JTabbedPane.WRAP_TAB_LAYOUT);

    // Recent files
    ArrayList<File> recentFilesList = new ArrayList<File>();
    for (int i = 1; i <= KseFrame.RECENT_FILES_SIZE; i++) {
      String recentFile = preferences.get(KSE3_RECENTFILE + i, null);

      if (recentFile == null) {
        break;
      } else {
        recentFilesList.add(cleanFilePath(new File(recentFile)));
      }
    }
    recentFiles = recentFilesList.toArray(new File[recentFilesList.size()]);

    // Current directory
    String currentDirectoryStr = preferences.get(KSE3_CURRENTDIR, null);
    if (currentDirectoryStr != null) {
      currentDirectory = cleanFilePath(new File(currentDirectoryStr));
    }

    // Look and feel
    lookAndFeelClass = preferences.get(KSE3_LOOKFEEL, null);
    lookAndFeelDecorated = preferences.getBoolean(KSE3_LOOKFEELDECOR, false);

    // Licensing
    licenseAgreed = preferences.getBoolean(KSE3_LICENSEAGREED, false);

    // Tip of the day
    showTipsOnStartUp = preferences.getBoolean(KSE3_TIPSONSTARTUP, true);
    nextTipIndex = preferences.getInt(KSE3_TIPINDEX, 0);

    // Default distinguished name
    defaultDN = preferences.get(KSE3_DEFAULTDN, "");

    // SSL host names and ports for "Examine SSL"
    sslHosts = preferences.get(KSE3_SSLHOSTS, "www.google.com;www.amazon.com");
    sslPorts = preferences.get(KSE3_SSLPORTS, "443");

    // auto update check
    autoUpdateCheckEnabled = preferences.getBoolean(KSE3_AUTO_UPDATE_CHECK_ENABLED, true);
    autoUpdateCheckInterval = preferences.getInt(KSE3_AUTO_UPDATE_CHECK_INTERVAL, 14);
    autoUpdateCheckLastCheck = getDate(preferences, KSE3_AUTO_UPDATE_CHECK_LAST_CHECK, new Date());

    // PKCS#11 libraries
    p11Libs = preferences.get(KSE3_PKCS11_LIBS, "");
  }