Esempio n. 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;
    }
Esempio n. 2
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));
      }
    }
  }
Esempio n. 3
0
 public String dump() {
   StringBuilder builder = new StringBuilder();
   for (Entry entry : entries.values()) {
     builder.append(Hex.encodeHex(entry.info.getPeerId().getBytes()));
     builder.append("\t");
     builder.append(entry.info.getAddress().getHostAddress());
     builder.append("\t");
     builder.append(entry.info.getPort());
     builder.append("\t");
     builder.append(this.toString());
     builder.append("\t");
     builder.append(ourId.distance(entry.info.getPeerId()));
     builder.append("\t");
     builder.append(new Date(entry.firstAdded));
     builder.append("\t");
     builder.append(new Date(entry.lastUpdate));
     builder.append("\t");
     builder.append(new Date(entry.lastPinged));
     builder.append("\t");
     builder.append(entry.pingAttempts);
     builder.append("\t");
     builder.append(entry.totalPings);
     builder.append("\n");
   }
   return builder.toString();
 }
Esempio n. 4
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;
  }
Esempio n. 5
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();
  }
  @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();
  }
Esempio n. 7
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));
  }
Esempio n. 8
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));
      }
    }
  }
  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;
  }
Esempio n. 10
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;
 }
Esempio n. 11
0
 @NotNull
 private String createRemoteFile(
     @NotNull ObjectId id, @NotNull ObjectLoader loader, @NotNull Uploader uploader)
     throws IOException {
   // Create LFS stream.
   final String hash;
   final String cached = cacheSha256.get(id.name());
   long size = 0;
   if (cached == null) {
     final MessageDigest md = createSha256();
     try (InputStream istream = loader.openStream()) {
       byte[] buffer = new byte[0x10000];
       while (true) {
         int read = istream.read(buffer);
         if (read <= 0) break;
         md.update(buffer, 0, read);
         size += read;
       }
     }
     hash = new String(Hex.encodeHex(md.digest(), true));
     cacheSha256.put(id.name(), hash);
     cache.commit();
   } else {
     hash = cached;
   }
   uploader.upload(id, new Meta(hash, size));
   return hash;
 }
  /**
   * Generates a hexadecimal {@link String} representation of 20 random bytes, produced by {@link
   * DefaultSecureRandomService#nextBytes(byte[])}.
   *
   * <p>The generated {@link String} is 40 characters in length and is composed of characters in the
   * range '0'-'9' and 'a'-'f'.
   *
   * <p>The length (20 bytes / 160 bits) was selected as it is the same as the size of the internal
   * state of the SHA1PRNG.
   *
   * @return returns a hexadecimal encoded representation of 20 random bytes.
   */
  public String generateToken() {
    byte[] bytes = new byte[TOKEN_LENGTH_BYTES];

    randomService.nextBytes(bytes);

    // can replace this with Hex.encodeHexString(bytes) when we upgrade to commons-codec 1.4.
    return new String(Hex.encodeHex(bytes));
  }
Esempio n. 13
0
 public static String makeMD5signature(byte[] source) throws AutomationFrameworkException {
   try {
     MessageDigest md = MessageDigest.getInstance("MD5");
     byte[] thedigest = md.digest(source);
     return new String(Hex.encodeHex(thedigest));
   } catch (NoSuchAlgorithmException e) {
     throw new AutomationFrameworkException("Exception on byte array processing.", e);
   }
 }
Esempio n. 14
0
 public String dump() {
   StringBuilder builder = new StringBuilder();
   builder.append(Hex.encodeHex(ourId.getBytes()));
   builder.append("\n");
   for (Bucket bucket : buckets) {
     builder.append(bucket.dump());
   }
   return builder.toString();
 }
 void encodeHex(Text val, FsEntry entry, String field) {
   Object o = entry.get(field);
   if (o != null && o instanceof byte[]) {
     byte[] b = (byte[]) o;
     val.set(new String(Hex.encodeHex(b)));
   } else {
     LOG.warn(entry.fullPath() + " didn't have a hash for " + field);
     val.set("");
   }
 }
Esempio n. 16
0
 private String generateId(String entropy) {
   try {
     MessageDigest cript = MessageDigest.getInstance("SHA-1");
     cript.reset();
     cript.update(entropy.getBytes());
     return new String(Hex.encodeHex(cript.digest()));
   } catch (NoSuchAlgorithmException ex) {
     return null;
   }
 }
Esempio n. 17
0
 public String hash(String hashType, String password) {
   try {
     MessageDigest md = MessageDigest.getInstance(hashType);
     md.update(password.getBytes(charset));
     byte[] raw = md.digest();
     return new String(Hex.encodeHex(raw));
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Esempio n. 18
0
 public static String encrypt(String plainText, String password) throws Exception {
   byte[] preSharedKey = password.getBytes();
   byte[] data = plainText.getBytes("UTF-8");
   SecretKey aesKey = new SecretKeySpec(preSharedKey, "AES");
   Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
   cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(preSharedKey));
   byte[] output = cipher.doFinal(data);
   String encryptedString = new String(Hex.encodeHex(output));
   return encryptedString.toUpperCase();
 }
Esempio n. 19
0
  /**
   * Sets the value of this form control.
   *
   * <p>The bound instance data is updated and the event sequence for this control is executed.
   * Event sequences are described in Chapter 4.6 of XForms 1.0 Recommendation.
   *
   * @param data the raw data.
   * @param filename the filename of the uploaded data.
   * @param mediatype the mediatype of the uploaded data.
   */
  public void setValue(byte[] data, String filename, String mediatype) throws XFormsException {
    if (!isBound()) {
      return;
    }

    String value;
    String name = filename;
    String type = mediatype;

    if (data != null && data.length > 0) {
      // get model item datatype
      Validator validator = this.model.getValidator();
      String datatype = getDatatype();

      // convert binary data according to bound datatype
      if (validator.isRestricted("base64Binary", datatype)) {
        value = new String(Base64.encodeBase64(data, true));
      } else if (validator.isRestricted("hexBinary", datatype)) {
        value = new String(Hex.encodeHex(data));
      } else if (validator.isRestricted("anyURI", datatype)) {
        value = new String(data);
      } else {
        throw new XFormsBindingException(
            "datatype not supported by upload control", this.target, datatype);
      }

      // check mediatype
      if (mediatype == null || mediatype.length() == 0) {
        type = DEFAULT_MEDIATYPE;
      }
    } else {
      value = "";
      name = "";
      type = "";
    }

    // update instance data
    Instance instance = this.model.getInstance(getInstanceId());
    instance.setNodeValue(getLocationPath(), value);
    ModelItem item = instance.getModelItem(getLocationPath());
    if (!item.isReadonly()) {
      item.setFilename(name);
      item.setMediatype(type);
    }

    // update helper elements
    if (this.filenameHelper != null) {
      this.filenameHelper.setValue(name);
    }
    if (this.mediatypeHelper != null) {
      this.mediatypeHelper.setValue(type);
    }

    dispatchValueChangeSequence();
  }
Esempio n. 20
0
  /**
   * Dumps the byte array as hex string to the {@link PrintStream}, with a title.
   *
   * @param title
   * @param buffer
   * @param pStream
   */
  public static void dumpAsHex(String title, byte[] buffer, PrintStream pStream) {
    String txt = "";
    if (!"".equalsIgnoreCase(title) && title != null) {
      txt = title + "  ";
    }
    if (buffer == null) txt += "NULL";
    else txt += "[size: " + buffer.length + " bytes]";
    pStream.println("----------------------------------------------------------  ----------------");
    pStream.println(txt);
    pStream.println("----------------------------------------------------------  ----------------");
    if (buffer == null) return;
    char[] chars = Hex.encodeHex(buffer);
    int charCount = 0;
    StringBuffer lineChars = new StringBuffer(16);
    int byteCount = 0, halfByteCount = 0, lineCount = 0;
    String regex = "[\\s\\e\\a\\x1f\0]";
    String replacement = " ";
    for (char ch : chars) {
      if (byteCount == 0 && halfByteCount == 0) {
        pStream.printf("%8X: ", lineCount * 16);
      }
      pStream.print(ch);
      if (halfByteCount == 1) {
        pStream.print(' ');

        lineChars.append(new String(new byte[] {buffer[charCount]}).charAt(0));
        // lineChars.append(new String(".").charAt(0));
        charCount++;
      }
      if (halfByteCount == 1) byteCount = ++byteCount % 16;
      if (byteCount == 8 && halfByteCount == 1) pStream.print(' ');
      if (byteCount == 0 && halfByteCount == 1) {
        if (charCount % 16 != 0) {
          // This here will probably never be called (check)
          for (int i = 0; i < 16 - charCount % 16; i++) pStream.print("   ");
          if (charCount % 16 < 8) pStream.print(' ');
        }
        pStream.print(" " + lineChars.toString().replaceAll(regex, replacement));
        lineChars = new StringBuffer(16);
        pStream.print('\n');
        lineCount++;
      }
      halfByteCount = ++halfByteCount % 2;
    }
    if (byteCount != 0) {
      if (charCount % 16 != 0) {
        for (int i = 0; i < 16 - charCount % 16; i++) pStream.print("   ");
        if (charCount % 16 < 8) pStream.print(' ');
      }
      pStream.print(" " + lineChars.toString().replaceAll(regex, replacement));
      lineChars = new StringBuffer(16);
      pStream.print('\n');
    }
    pStream.println("----------------------------------------------------------  ----------------");
  }
 private static String md5checksum(String toHash) {
   try {
     MessageDigest m = MessageDigest.getInstance("MD5");
     m.reset();
     m.update(toHash.getBytes(Charset.forName("UTF8")));
     byte[] digest = m.digest();
     return new String(Hex.encodeHex(digest));
   } catch (Exception ex) {
     return toHash;
   }
 } // (TESTED - cut and paste from proven PasswordEncryption class)
Esempio n. 22
0
 @Test
 public void Md5Test() throws Exception {
   byte[] bs;
   try {
     bs = Md5Encryp.encrypt(INFO);
     System.out.println("MD5加密后密文是:" + new String(Hex.encodeHex(bs)));
     //            Base64.encode(bs);
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   }
 }
Esempio n. 23
0
 public static String encodePassword(String rawPass, String salt) {
   String saltedPass = mergePasswordAndSalt(rawPass, salt, false);
   MessageDigest messageDigest = getMessageDigest();
   byte[] digest;
   try {
     digest = messageDigest.digest(saltedPass.getBytes("UTF-8"));
   } catch (UnsupportedEncodingException e) {
     throw new IllegalStateException("UTF-8 not supported!");
   }
   return new String(Hex.encodeHex(digest));
 }
Esempio n. 24
0
 public static String makeMd5Identifier(String identifier) {
   String result;
   try {
     MessageDigest md = MessageDigest.getInstance("MD5");
     md.reset();
     byte[] digest = md.digest(identifier.getBytes());
     result = String.valueOf(Hex.encodeHex(digest));
   } catch (NoSuchAlgorithmException e) {
     throw new RuntimeException(e);
   }
   return result;
 }
 private void writeVersion(String key, VectorClock version) {
   try {
     File versionFile = new File(getVersionDirectory(), key);
     if (!versionFile.exists() || versionFile.delete()) {
       // write the version file.
       String hexCode = new String(Hex.encodeHex(version.toBytes()));
       FileUtils.writeStringToFile(versionFile, hexCode, "UTF-8");
     }
   } catch (Exception e) {
     throw new VoldemortException("Failed to write Version for Key:" + key, e);
   }
 }
Esempio n. 26
0
 /**
  * Crypte une chaine de caractère pour qu'elle puisse être lue par le serveur.
  *
  * @param password La chaine à crypter.
  * @return La chaine cryptée.
  */
 private static String hashPassword(String password) {
   try {
     MessageDigest digest = MessageDigest.getInstance("SHA-1");
     digest.reset();
     digest.update(password.getBytes());
     return new String(Hex.encodeHex(digest.digest()));
   } catch (NoSuchAlgorithmException e) {
     // Algorithme indisponible
     System.out.println(e.getMessage());
     return new String();
   }
 }
Esempio n. 27
0
 public static String md5(String i) {
   try {
     MessageDigest messageDigest = MessageDigest.getInstance("MD5");
     messageDigest.reset();
     messageDigest.update(i.getBytes(Charset.forName("UTF8")));
     byte[] resultByte = messageDigest.digest();
     return new String(Hex.encodeHex(resultByte));
   } catch (Exception ex) {
     ex.printStackTrace();
     return "";
   }
 }
Esempio n. 28
0
 /**
  * Encodes the given string by using the hexadecimal representation of its UTF-8 bytes.
  *
  * @param s The string to encode.
  * @return The encoded string.
  */
 public static String utf8HexEncode(String s) {
   if (s == null) {
     return null;
   }
   byte[] utf8;
   try {
     utf8 = s.getBytes(ENCODING_UTF8);
   } catch (UnsupportedEncodingException x) {
     throw new RuntimeException(x);
   }
   return String.valueOf(Hex.encodeHex(utf8));
 }
Esempio n. 29
0
 public String toString() {
   return "fileId: "
       + fileId
       + ", fileVersion: "
       + fileVersion
       + ", offset: "
       + offset
       + ", length: "
       + length
       + ", hash: "
       + new String(Hex.encodeHex(hashKey));
 }
Esempio n. 30
0
  /**
   * Calculates the MD5 digest and returns the value as a 32 character hex string.
   *
   * @param s Data to digest.
   * @return MD5 digest as a hex string.
   */
  public static String md5Hex(String s) {
    if (s == null) {
      return null;
    }

    try {
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      return new String(Hex.encodeHex(md5.digest(s.getBytes(ENCODING_UTF8))));
    } catch (Exception x) {
      throw new RuntimeException(x.getMessage(), x);
    }
  }