Example #1
0
    /**
     * Get the uid of a card
     *
     * @return a String with the value of the uid (not empty)
     * @throws CardException in case of an error
     */
    public String call() throws Exception {
      String uid;
      try {
        // Connect to card and read
        Card card = terminal.connect("T=1");

        // Get the basic communication channel
        CardChannel channel = card.getBasicChannel();

        // Disable the buzzer
        channel.transmit(Commands.DISABLE_BUZZER);

        // Send data and retrieve output
        ResponseAPDU response = channel.transmit(Commands.READ);
        uid = new String(Hex.encodeHex(response.getData())).toUpperCase();
        if (!new String(Hex.encodeHex(response.getBytes())).endsWith("9000")) {
          // Unsuccessful response
          card.disconnect(true);
          throw new CardException(Errors.CARD_READ_FAILURE);
        }
        if (uid.isEmpty()) {
          // Empty response (should not happen, but heh)
          card.disconnect(true);
          throw new CardException(Errors.EMPTY_CODE);
        }
        card.disconnect(true);
      } catch (Smartcardio.JnaPCSCException e) {
        throw new CardException(Errors.NO_CARD);
      }
      return uid;
    }
Example #2
0
  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();
    }
  }
  @Override
  public U2fSignRequest getSignRequest(String accountName, String appId) throws U2FException {
    Log.info(">> getSignRequest " + accountName);

    List<SecurityKeyData> securityKeyDataList = dataStore.getSecurityKeyData(accountName);

    byte[] challenge = challengeGenerator.generateChallenge(accountName);
    String challengeBase64 = Base64.encodeBase64URLSafeString(challenge);

    ImmutableList.Builder<RegisteredKey> registeredKeys = ImmutableList.builder();
    Log.info("  challenge: " + Hex.encodeHexString(challenge));
    for (SecurityKeyData securityKeyData : securityKeyDataList) {
      SignSessionData sessionData =
          new SignSessionData(accountName, appId, challenge, securityKeyData.getPublicKey());
      String sessionId = dataStore.storeSessionData(sessionData);

      byte[] keyHandle = securityKeyData.getKeyHandle();
      List<Transports> transports = securityKeyData.getTransports();
      Log.info("-- Output --");
      Log.info("  sessionId: " + sessionId);
      Log.info("  keyHandle: " + Hex.encodeHexString(keyHandle));

      String keyHandleBase64 = Base64.encodeBase64URLSafeString(keyHandle);

      Log.info("<< getRegisteredKey " + accountName);
      registeredKeys.add(
          new RegisteredKey(U2FConsts.U2F_V2, keyHandleBase64, transports, appId, sessionId));
    }

    return new U2fSignRequest(challengeBase64, registeredKeys.build());
  }
Example #4
0
  public static byte[] publicKeyToAddress(String string) {

    byte[] publicKeyBytes = null;

    try {
      publicKeyBytes = org.apache.commons.codec.binary.Hex.decodeHex(string.toCharArray());
    } catch (DecoderException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    // System.out.println(Utils.toHex(publicKeyBytes));
    // System.out.println(publicKeyBytes.length);
    byte[] out = new byte[20];
    byte[] hash = new byte[256];
    byte[] hash2 = new byte[256];

    try {
      MessageDigest digest = MessageDigest.getInstance("SHA-256");
      hash = digest.digest(publicKeyBytes);
      hash2 = digest.digest(hash);
      RIPEMD160Digest digest160 = new RIPEMD160Digest();
      digest160.update(hash, 0, hash.length);
      digest160.doFinal(out, 0);

    } catch (Exception e) {
      // TODO: handle exception
    }

    byte[] ripemd_bytes = null;
    byte[] checksum = new byte[4];

    try {
      ripemd_bytes =
          org.apache.commons.codec.binary.Hex.decodeHex(
              ("00" + Utils.toHex(out).toUpperCase()).toCharArray());
    } catch (DecoderException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    try {
      MessageDigest digest = MessageDigest.getInstance("SHA-256");
      hash = digest.digest(ripemd_bytes);
      hash2 = digest.digest(hash);

    } catch (Exception e) {
      // TODO: handle exception
    }

    System.arraycopy(hash2, 0, checksum, 0, checksum.length);
    byte[] combined = new byte[1 + out.length + checksum.length];

    for (int i = 0; i < combined.length; ++i) {
      combined[i] = i < ripemd_bytes.length ? ripemd_bytes[i] : checksum[i - ripemd_bytes.length];
    }

    // System.out.println(Utils.toHex(combined));
    return (combined);
  }
Example #5
0
    @Override
    public void process(InputStream in, OutputStream out) throws IOException {
      int len;
      byte[] inBuf = new byte[8192];
      Hex h = new Hex();
      while ((len = in.read(inBuf)) > 0) {
        // If the input buffer is of odd length, try to get another byte
        if (len % 2 != 0) {
          int b = in.read();
          if (b != -1) {
            inBuf[len] = (byte) b;
            len++;
          }
        }

        // Construct a new buffer bounded to len
        byte[] slice = Arrays.copyOfRange(inBuf, 0, len);
        try {
          out.write(h.decode(slice));
        } catch (DecoderException ex) {
          throw new IOException(ex);
        }
      }
      out.flush();
    }
Example #6
0
  private static void bcDES() throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    // Key convert
    DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
    SecretKeyFactory factory = SecretKeyFactory.getInstance("DES", "BC");
    SecretKey desKey = factory.generateSecret(desKeySpec);

    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, desKey);

    System.out.println("BC" + cipher.getProvider());

    byte[] result = cipher.doFinal("ABC".getBytes());
    String hexResult = Hex.encodeHexString(result);
    System.out.println(hexResult);

    cipher.init(Cipher.DECRYPT_MODE, desKey);
    result =
        cipher.doFinal(
            Hex.decodeHex(hexResult.toCharArray())
            // result
            );
    System.out.println(new String(result));
  }
Example #7
0
  /**
   * Checks if the {@code TimeStampToken} matches the signed data.
   *
   * @param data the array of {@code byte} representing the timestamped data
   * @return true if the data is verified by the TimeStampToken
   */
  public boolean matchData(final byte[] data) {

    try {

      messageImprintData = data != null;
      final TimeStampTokenInfo timeStampInfo = timeStamp.getTimeStampInfo();
      final ASN1ObjectIdentifier hashAlgorithm = timeStampInfo.getHashAlgorithm().getAlgorithm();
      final DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(hashAlgorithm.getId());

      final byte[] computedDigest = DSSUtils.digest(digestAlgorithm, data);
      final byte[] timestampDigest = timeStampInfo.getMessageImprintDigest();
      messageImprintIntact = Arrays.equals(computedDigest, timestampDigest);
      if (!messageImprintIntact) {
        logger.error(
            "Computed digest ({}) on the extracted data from the document : {}",
            digestAlgorithm,
            Hex.encodeHexString(computedDigest));
        logger.error("Digest present in TimestampToken: {}", Hex.encodeHexString(timestampDigest));
        logger.error(
            "Digest in TimestampToken matches digest of extracted data from document: {}",
            messageImprintIntact);
      }
    } catch (DSSException e) {

      messageImprintIntact = false;
      signedDataMessage = "Timestamp digest problem: " + e.getMessage();
    }
    return messageImprintIntact;
  }
Example #8
0
 public static String decodeString(String encodedStr) {
   String encodeStr = "$#TGDF*FAA&21we@VGXD532w23413!";
   String tempStr = "";
   try {
     if (encodedStr == null) {
       encodedStr = "";
     }
     // encodedStr = new String(Hex.decodeHex(encodedStr.toCharArray()));
     Hex hex = new Hex();
     encodedStr = new String(hex.decode(encodedStr.getBytes("GBK")), "GBK");
     int i = 0;
     int j = 0;
     for (i = 0; i < encodedStr.length(); i++) {
       if (j >= encodeStr.length()) {
         j = 0;
       }
       char truePass = (char) ~(encodedStr.charAt(i) ^ ~encodeStr.charAt(j));
       tempStr = tempStr + truePass;
       j++;
     }
   } catch (Exception ex) {
     throw new RuntimeException(ex.getMessage());
   }
   return tempStr;
 }
Example #9
0
  @Test
  public void testSplitQuery() throws Exception {
    // Insert 20 rows per shard
    for (String shardName : testEnv.shardKidMap.keySet()) {
      Util.insertRowsInShard(testEnv, shardName, 20);
    }
    Util.waitForTablet("rdonly", 40, 3, testEnv);
    VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
    Map<Query, Long> queries =
        vtgate.splitQuery("test_keyspace", "select id,keyspace_id from vtgate_test", 1);
    vtgate.close();

    // Verify 2 splits, one per shard
    Assert.assertEquals(2, queries.size());
    Set<String> shardsInSplits = new HashSet<>();
    for (Query q : queries.keySet()) {
      Assert.assertEquals("select id,keyspace_id from vtgate_test", q.getSql());
      Assert.assertEquals("test_keyspace", q.getKeyspace());
      Assert.assertEquals("rdonly", q.getTabletType());
      Assert.assertEquals(0, q.getBindVars().size());
      Assert.assertEquals(null, q.getKeyspaceIds());
      String start = Hex.encodeHexString(q.getKeyRanges().get(0).get("Start"));
      String end = Hex.encodeHexString(q.getKeyRanges().get(0).get("End"));
      shardsInSplits.add(start + "-" + end);
    }

    // Verify the keyrange queries in splits cover the entire keyspace
    Assert.assertTrue(shardsInSplits.containsAll(testEnv.shardKidMap.keySet()));
  }
  /**
   * Convert a public key to the SSH format.
   *
   * <p>Note that only RSA keys are supported at the moment.
   *
   * @param key the public key to convert
   * @return an array of bytes that can with the representation of the public key
   */
  public static byte[] getKeyBytes(final PublicKey key) {
    // We only support RSA at the moment:
    if (!(key instanceof RSAPublicKey)) {
      log.error(
          "The key algorithm \"" + key.getAlgorithm() + "\" is not supported, will return null.");
      return null;
    }

    // Extract the bytes of the exponent and the modulus
    // of the key:
    final RSAPublicKey rsaKey = (RSAPublicKey) key;
    final byte[] exponentBytes = rsaKey.getPublicExponent().toByteArray();
    final byte[] modulusBytes = rsaKey.getModulus().toByteArray();
    if (log.isDebugEnabled()) {
      log.debug(
          "Exponent is "
              + rsaKey.getPublicExponent()
              + " ("
              + Hex.encodeHexString(exponentBytes)
              + ").");
      log.debug(
          "Modulus is " + rsaKey.getModulus() + " (" + Hex.encodeHexString(exponentBytes) + ").");
    }

    try {
      // Prepare the stream to write the binary SSH key:
      final ByteArrayOutputStream binaryOut = new ByteArrayOutputStream();
      final DataOutputStream dataOut = new DataOutputStream(binaryOut);

      // Write the SSH header (4 bytes for the length of the algorithm
      // name and then the algorithm name):
      dataOut.writeInt(SSH_RSA.length());
      dataOut.writeBytes(SSH_RSA);

      // Write the exponent and modulus bytes (note that it is not
      // necessary to check if the most significative bit is one, as
      // that will never happen with byte arrays created from big
      // integers, unless they are negative, which is not the case
      // for RSA modulus or exponents):
      dataOut.writeInt(exponentBytes.length);
      dataOut.write(exponentBytes);
      dataOut.writeInt(modulusBytes.length);
      dataOut.write(modulusBytes);

      // Done, extract the bytes:
      binaryOut.close();
      final byte[] keyBytes = binaryOut.toByteArray();
      if (log.isDebugEnabled()) {
        log.debug("Key bytes are " + Hex.encodeHexString(keyBytes) + ".");
      }

      return keyBytes;
    } catch (IOException exception) {
      log.error("Error while serializing public key, will return null.", exception);
      return null;
    }
  }
Example #11
0
 public String decrypt(String valor, String chave, String vetor) throws Exception {
   byte[] v = Hex.decodeHex(valor.toCharArray());
   byte[] c = Hex.decodeHex(chave.toCharArray());
   byte[] iv = Hex.decodeHex(vetor.toCharArray());
   SecretKeySpec k = new SecretKeySpec(c, "AES");
   AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
   Cipher dcipher = Cipher.getInstance("AES/CBC/NoPadding");
   dcipher.init(Cipher.DECRYPT_MODE, k, paramSpec);
   return new String(dcipher.doFinal(v)).replaceAll("\0", "");
 }
Example #12
0
  @SuppressWarnings("unchecked")
  public static void main_3(String[] args) throws IOException {

    PDDocument doc = PDDocument.load(iconFile);

    List<PDPage> pages = doc.getDocumentCatalog().getAllPages();

    List<COSObject> objects = doc.getDocument().getObjects();

    for (COSObject cosObject : objects) {

      COSBase cosbase = cosObject.getObject();

      if (cosObject.getObject() instanceof COSStream) {

        COSStream cosstream = (COSStream) cosbase;

        COSBase filter = cosstream.getDictionaryObject(COSName.FILTER);

        COSBase subtype = cosstream.getDictionaryObject(COSName.SUBTYPE);

        if (subtype != null && subtype.equals(COSName.IMAGE)) {

          System.out.println(filter);

          InputStream filtered = cosstream.getFilteredStream();
          // PDStream stream = new PDStream(costream);

          System.out.println(Hex.encodeHex(IOUtils.toByteArray(filtered)));
        }
      }
    }

    for (PDPage pdPage : pages) {

      PDResources resources = pdPage.getResources();

      Map<String, PDXObject> images = resources.getXObjects();

      Set<String> keys = images.keySet();

      for (String key : keys) {

        PDXObject image = images.get(key);

        byte[] imgData = image.getPDStream().getByteArray();

        System.out.println(Hex.encodeHex(imgData));
      }
    }
  }
  @Override
  public boolean importData(TransferSupport support) throws ConverterException {
    try {
      if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
        List<File> files =
            (List<File>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
        for (File file : files) {
          FileInputStream fis = null;
          OutputStream out = null;
          try {
            out = getOutputStream(file, ".hex");
            fis = new FileInputStream(file);
            byte[] buffer = new byte[bufferSize];
            int count = 0;
            while (-1 != (count = fis.read(buffer))) {
              if (count == bufferSize) {
                out.write(Hex.encodeHexString(buffer).getBytes("UTF-8"));
              } else {
                byte[] tmp = Arrays.copyOf(Hex.encodeHexString(buffer).getBytes("UTF-8"), count);
                out.write(tmp);
              }
            }
          } catch (Exception e) {
            throw new ConverterException(e);
          } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(fis);
          }
        }
        return true;
      } else if (support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
        OutputStream out = null;
        try {
          byte[] encode = Hex.encodeHexString(data.getBytes()).getBytes();
          out = getOutputStream(null, ".hex");
          out.write(encode);
        } catch (Exception e) {
          throw new ConverterException(e);
        } finally {
          IOUtils.closeQuietly(out);
        }
      }
    } catch (Exception e) {
      throw new ConverterException(e);
    }

    return false;
  }
Example #14
0
 @NotNull
 private String createLocalFile(@NotNull ObjectId id, @NotNull ObjectLoader loader)
     throws IOException {
   // Create LFS stream.
   final File tmpFile = new File(tempPath, UUID.randomUUID().toString());
   final MessageDigest md = createSha256();
   try (InputStream istream = loader.openStream();
       OutputStream ostream = new FileOutputStream(tmpFile)) {
     byte[] buffer = new byte[0x10000];
     while (true) {
       int size = istream.read(buffer);
       if (size <= 0) break;
       ostream.write(buffer, 0, size);
       md.update(buffer, 0, size);
     }
   }
   final String hash = new String(Hex.encodeHex(md.digest(), true));
   cacheSha256.putIfAbsent(id.name(), hash);
   cache.commit();
   // Rename file.
   final File lfsFile =
       new File(
           basePath,
           "lfs/objects/" + hash.substring(0, 2) + "/" + hash.substring(2, 4) + "/" + hash);
   makeParentDirs(lfsFile.getParentFile());
   if (lfsFile.exists()) {
     if (!tmpFile.delete()) {
       log.warn("Can't delete temporary file: {}", lfsFile.getAbsolutePath());
     }
   } else if (!tmpFile.renameTo(lfsFile)) {
     throw new IOException("Can't rename file: " + tmpFile + " -> " + lfsFile);
   }
   return hash;
 }
Example #15
0
  public static void main(String[] args)
      throws DocumentException, MalformedURLException, IOException {

    BufferedImage image = ImageIO.read(imageFile);

    BufferedImage bi =
        new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
    ColorConvertOp xformOp = new ColorConvertOp(null);
    xformOp.filter(image, bi);

    // bi.setData(icon.getData());

    WritableRaster raster = bi.getRaster();
    DataBufferInt data = (DataBufferInt) raster.getDataBuffer();

    int[] intData = data.getData();

    ByteBuffer byteBuffer = ByteBuffer.allocate(intData.length * 4);
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    intBuffer.put(intData);

    byte[] array = byteBuffer.array();

    System.out.println(Hex.encodeHex(array));
  }
  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();
  }
  public String calculateHash(String graph) throws SQLException, NoSuchAlgorithmException {
    // TODO: sanitize graph

    MessageDigest digest = MessageDigest.getInstance("SHA-512"); // takes 50 sec on Fly data
    //		MessageDigest digest = MessageDigest.getInstance("MD5"); // takes 46 sec on Fly data

    // cb66cc5f1feb5169542af48342936ad2962a8ae14840f1e029028636004f779346c19ecd0917ea2f53c6ec94f4ab10c5bffc272888ae33b73797bdee9cb7193a

    Statement st = con.createStatement();
    try {

      ResultSet rs =
          executeQuery(st, "SPARQL SELECT ?s ?p ?o FROM <" + graph + "> WHERE { ?s ?p ?o . }");
      while (rs.next()) {
        digest.update(rs.getString(1).getBytes());
        digest.update(rs.getString(2).getBytes());
        digest.update(rs.getString(3).getBytes());
      }

    } catch (VirtuosoException ex) {
      rethrowWithTips(ex);
    }
    String hexString = new String(Hex.encodeHex(digest.digest()));
    return hexString;
  }
Example #18
0
  public String asHexToken(Key key) {
    try {
      Cipher encodingCipher = Cipher.getInstance("AES");
      encodingCipher.init(Cipher.ENCRYPT_MODE, key);

      ByteBuffer buffer = ByteBuffer.allocate(16 + 1 + 8 + 8 + getBufferSize());
      buffer.position(16);
      buffer.put(getId());
      buffer.putLong(getExpires().getTimeInMillis());
      buffer.putLong(getUoid());
      getBytes(buffer);
      if (buffer.position() != buffer.capacity()) {
        throw new RuntimeException(
            "Buffer's position should be at the end "
                + buffer.position()
                + "/"
                + buffer.capacity());
      }
      MessageDigest messageDigest = MessageDigest.getInstance("MD5");
      buffer.position(16);
      messageDigest.update(buffer);
      buffer.position(0);
      buffer.put(messageDigest.digest());

      byte[] encodedBytes = encodingCipher.doFinal(buffer.array());
      String encodedHexString = new String(Hex.encodeHex(encodedBytes));
      return encodedHexString;
    } catch (Exception e) {
      LOGGER.error("", e);
    }
    return null;
  }
Example #19
0
 /** Hex解码. */
 public static byte[] decodeHex(String input) {
   try {
     return Hex.decodeHex(input.toCharArray());
   } catch (DecoderException e) {
     throw Exceptions.unchecked(e);
   }
 }
  /**
   * Create the application.
   *
   * @throws DecoderException
   * @throws SocketException
   */
  public VideoSubscriberGUI() throws DecoderException, SocketException {
    initialize();

    // Setup the Blackadder environment.
    String sharedObjPath = ProjectPropertiesSingleton.getInstance().getProperty("BAWrapperPath");
    BlackadderWrapper.configureObjectFile(sharedObjPath);
    client = BlackAdderClient.getInstance();
    channelID = 1;

    // Initialise the rootscope
    // publish the root scope where all videos will be published
    String rootScopeStr = "1111111111111111";
    ByteIdentifier rootId = new ByteIdentifier(Hex.decodeHex(rootScopeStr.toCharArray()));
    rootScope = new ScopeID(rootId);

    // immediately subscribe to the catalog
    videoSubscriber = new VideoSubscriber(client, rootScope, strategy);

    // initialise ridMappings
    ridMappings = new HashMap<String, String>();

    // Start the event handler
    SubscriberEventHandler handler = new SubscriberEventHandler(this);
    handler.start();
  }
Example #21
0
  public static byte[] privateKeyToWif(String string, boolean testnet) {

    string = testnet ? "EF" + string : "80" + string;

    byte[] privateKeyBytes = new byte[string.length()];
    byte[] checksum = new byte[4];
    try {
      privateKeyBytes = org.apache.commons.codec.binary.Hex.decodeHex(string.toCharArray());
    } catch (DecoderException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    byte[] hash = new byte[256];
    byte[] hash2 = new byte[256];
    try {
      MessageDigest digest = MessageDigest.getInstance("SHA-256");
      hash = digest.digest(privateKeyBytes);
      hash2 = digest.digest(hash);

    } catch (Exception e) {
      // TODO: handle exception
    }

    System.arraycopy(hash2, 0, checksum, 0, checksum.length);

    byte[] combined = new byte[privateKeyBytes.length + checksum.length];

    for (int i = 0; i < combined.length; ++i) {
      combined[i] =
          i < privateKeyBytes.length ? privateKeyBytes[i] : checksum[i - privateKeyBytes.length];
    }

    return (combined);
  }
Example #22
0
 public Day4(String input) {
   super(input);
   try {
     MessageDigest md = MessageDigest.getInstance("MD5");
     boolean foundFiveZeroesNumber = false;
     boolean foundSixZeroesNumber = false;
     for (int i = 0; ; i++) {
       byte[] bytesOfMessage = (input + i).getBytes("UTF-8");
       String digest = Hex.encodeHexString(md.digest(bytesOfMessage));
       if (!foundFiveZeroesNumber && digest.substring(0, 5).equals("00000")) {
         fiveZeroesNumber = i;
         foundFiveZeroesNumber = true;
       }
       if (!foundSixZeroesNumber && digest.substring(0, 6).equals("000000")) {
         sixZeroesNumber = i;
         foundSixZeroesNumber = true;
       }
       if (foundFiveZeroesNumber && foundSixZeroesNumber) {
         break;
       }
     }
   } catch (Exception e) {
     // Gotta catch em all!
     System.out.println("something happened :(");
   }
 }
Example #23
0
  public static void main_2(String[] args) throws IOException, DocumentException {

    PdfReader reader = new PdfReader(iconFile.getAbsolutePath());

    for (int i = 0; i < reader.getXrefSize(); i++) {

      PdfObject pdfobj = reader.getPdfObject(i);

      if (pdfobj == null || !pdfobj.isStream()) {
        continue;
      }

      PdfStream stream = (PdfStream) pdfobj;
      PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE);

      if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) {

        System.out.println(stream);

        byte[] imgData = PdfReader.getStreamBytesRaw((PRStream) stream);

        System.out.println(Hex.encodeHex(imgData));
      }
    }
  }
Example #24
0
 /** Hex解码. */
 public static byte[] decodeHex(String input) {
   try {
     return Hex.decodeHex(input.toCharArray());
   } catch (DecoderException e) {
     throw new HeheRuntimeException(e);
   }
 }
Example #25
0
  @Test
  public void test()
      throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException,
          CertificateException, IOException, InvalidKeyException, NoSuchProviderException,
          SignatureException, DecoderException {
    byte[] assinatura = SignerSample.signTestFile();
    assertTrue(assinatura != null);
    String saida = Hex.encodeHexString(assinatura);
    logger.debug("Assinatura: " + saida);

    // Verifica a assinatura:
    InputStream filepath = SignerSample.class.getClassLoader().getResourceAsStream("arquivo.txt");
    byte[] bTexto = IOUtils.toByteArray(filepath);
    String texto = new String(bTexto, "UTF-8");
    logger.debug("Texto: " + texto);
    boolean resultado = VerifySignature.verify(saida, texto, "*", "meucertificado", "teste001");
    assertTrue(resultado);

    /*

      	// Verifica com keystore externa (troque o path antes de rodar esse teste)
      	resultado = VerifySignature.verify(saida, texto,
    		"/home/cleuton/wsDropwizard01/certstore/verifykeystore.jks",
    		"meucertificado", "teste001");
      	assertTrue(resultado);
    */

    // Altera o texto e verifica novamente:
    bTexto[5] = 61;
    String texto2 = new String(bTexto, "UTF-8");
    resultado = VerifySignature.verify(saida, texto2, "*", "meucertificado", "teste001");
    assertFalse(resultado);
  }
  @Override
  public void send(Quad quad) {
    try {
      byte[] s = tdbloader3.serialize(quad.getSubject()).getBytes("UTF-8");
      byte[] p = tdbloader3.serialize(quad.getPredicate()).getBytes("UTF-8");
      byte[] o = tdbloader3.serialize(quad.getObject()).getBytes("UTF-8");
      byte[] g = null;
      // Union graph?!
      if (!quad.isTriple() && !quad.isDefaultGraph())
        g = tdbloader3.serialize(quad.getGraph()).getBytes("UTF-8");

      digest.reset();
      digest.update(s); // TODO: should we do something better here?
      digest.update(p);
      digest.update(o);
      if (g != null) digest.update(g.toString().getBytes("UTF-8"));

      String md5 = new String(Hex.encodeHex(digest.digest()));
      sdb01.add(new Pair<byte[], byte[]>(s, (md5 + "|s").getBytes("UTF-8")));
      sdb01.add(new Pair<byte[], byte[]>(p, (md5 + "|p").getBytes("UTF-8")));
      sdb01.add(new Pair<byte[], byte[]>(o, (md5 + "|o").getBytes("UTF-8")));
      if (g != null) sdb01.add(new Pair<byte[], byte[]>(g, (md5 + "|g").getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
      throw new AtlasException(e);
    }

    monitor.tick();
  }
Example #27
0
 /**
  * Get the content body.
  *
  * @return the content
  */
 public String getContent() {
   if (StringUtils.hasText(content)) {
     return content;
   } else if (StringUtils.hasText(contentResourcePath) && contentType.startsWith("text")) {
     try {
       return FileUtils.readToString(
           new PathMatchingResourcePatternResolver()
               .getResource(contentResourcePath)
               .getInputStream(),
           Charset.forName(charsetName));
     } catch (IOException e) {
       throw new CitrusRuntimeException("Failed to read SOAP attachment file resource", e);
     }
   } else {
     try {
       byte[] binaryData =
           FileUtils.readToString(getDataHandler().getInputStream(), Charset.forName(charsetName))
               .getBytes(Charset.forName(charsetName));
       if (encodingType.equals(SoapAttachment.ENCODING_BASE64_BINARY)) {
         return Base64.encodeBase64String(binaryData);
       } else if (encodingType.equals(SoapAttachment.ENCODING_HEX_BINARY)) {
         return Hex.encodeHexString(binaryData).toUpperCase();
       } else {
         throw new CitrusRuntimeException(
             String.format(
                 "Unsupported encoding type '%s' for SOAP attachment - choose one of %s or %s",
                 encodingType,
                 SoapAttachment.ENCODING_BASE64_BINARY,
                 SoapAttachment.ENCODING_HEX_BINARY));
       }
     } catch (IOException e) {
       throw new CitrusRuntimeException("Failed to read SOAP attachment data input stream", e);
     }
   }
 }
Example #28
0
 /** Hex解码. */
 public static byte[] hexDecode(String input) {
   try {
     return Hex.decodeHex(input.toCharArray());
   } catch (DecoderException e) {
     throw new IllegalStateException("Hex Decoder exception", e);
   }
 }
Example #29
0
  public static byte[] addrHashToScriptPubKey(String string) throws DecoderException {
    // TODO Auto-generated method stub
    // return b'76a914' + codecs.encode(utils.base58CheckDecode(b58str),'hex')  + b'88ac'

    return org.apache.commons.codec.binary.Hex.decodeHex(
        ("76a914" + Utils.toHex(Base58Check.decode(string)) + "88ac").toCharArray());
  }
Example #30
0
  /**
   * Returns the certificate hash
   *
   * @param certificate the certificate
   * @return the certificate hash
   * @throws GeneralSecurityException
   */
  protected byte[] getHash(byte[] certificate) throws GeneralSecurityException {
    String hash256;

    hash256 =
        new String(Hex.encodeHex(MessageDigest.getInstance("SHA-256").digest(certificate), false));
    return format(hash256).getBytes();
  }