List of usage examples for java.lang Character forDigit
public static char forDigit(int digit, int radix)
From source file:org.lwes.util.NumberCodec.java
/** * Return a String encoding the bytes from a portion of a byte array * in hex form./*from w w w. j av a 2s . c o m*/ * * @param bytes the byte array * @param offset the first byte to output * @param length the number of bytes to output * @return the hex dump of the byte array */ public static String byteArrayToHexString(byte[] bytes, int offset, int length) { StringBuffer buf = new StringBuffer(2 * length); for (int i = offset; i < offset + length; i++) { buf.append(Character.forDigit(((bytes[i] >>> 4) & 0x0f), 16)); buf.append(Character.forDigit((bytes[i] & 0x0f), 16)); } return buf.toString(); }
From source file:com.jjoe64.graphview_demos.fragments.CollectData.java
private String IntToHex2(int Value) { char HEX2[] = { Character.forDigit((Value >> 4) & 0x0F, 16), Character.forDigit(Value & 0x0F, 16) }; String Hex2Str = new String(HEX2); return Hex2Str; }/* w w w .ja v a 2 s .co m*/
From source file:com.amalto.webapp.core.util.Util.java
/** * Returns a string in the hexadecimal format. * //from w w w . j a v a2s. c om * @param bytes the converted bytes * @return the hexadecimal string representing the bytes data * @throws IllegalArgumentException if the byte array is null */ public static String toHexString(byte[] bytes) { if (bytes == null) { throw new IllegalArgumentException("byte array must not be null"); //$NON-NLS-1$ } StringBuilder hex = new StringBuilder(bytes.length * 2); for (byte aByte : bytes) { hex.append(Character.forDigit((aByte & 0XF0) >> 4, 16)); hex.append(Character.forDigit((aByte & 0X0F), 16)); } return hex.toString(); }
From source file:jp.ksksue.app.terminal.AndroidUSBSerialMonitorLite.java
private String IntToHex2(int Value) { char HEX2[] = { Character.forDigit((Value >> 4) & 0x0F, 16), Character.forDigit(Value & 0x0F, 16) }; String Hex2Str = new String(HEX2); return Hex2Str; }
From source file:org.pentaho.platform.repository.RepositoryFilenameUtils.java
/** * Performs percent-encoding (as specified in {@code IUnifiedRepository}) on given {@code name}, only encoding * the characters given in {@code reservedChars}. Assumes only ASCII characters in reservedChars. * /*from ww w . ja va2 s . c om*/ * @param name * name to escape * @param reservedChars * chars within name to escape * @return escaped name */ public static String escape(final String name, final List<Character> reservedChars) { if (name == null || reservedChars == null) { throw new IllegalArgumentException(); } if (reservedChars.contains(escapeChar)) { // we can't use % as escape char if it is illegal throw new IllegalArgumentException(); } List<Character> mergedReservedChars = new ArrayList<Character>(reservedChars); mergedReservedChars.add(escapeChar); // have to have this one StringBuilder buffer = new StringBuilder(name.length() * 2); for (int i = 0; i < name.length(); i++) { char ch = name.charAt(i); if (mergedReservedChars.contains(ch)) { buffer.append(escapeChar); buffer.append(Character.toUpperCase(Character.forDigit(ch / 16, 16))); buffer.append(Character.toUpperCase(Character.forDigit(ch % 16, 16))); } else { buffer.append(ch); } } return buffer.toString(); }
From source file:org.apache.hadoop.hdfs.TestDFSShell.java
private void textTest(Path root, Configuration conf) throws Exception { PrintStream bak = null;//ww w . j av a 2 s .c o m try { final FileSystem fs = root.getFileSystem(conf); fs.mkdirs(root); // Test the gzip type of files. Magic detection. OutputStream zout = new GZIPOutputStream(fs.create(new Path(root, "file.gz"))); Random r = new Random(); bak = System.out; ByteArrayOutputStream file = new ByteArrayOutputStream(); for (int i = 0; i < 1024; ++i) { char c = Character.forDigit(r.nextInt(26) + 10, 36); file.write(c); zout.write(c); } zout.close(); ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); String[] argv = new String[2]; argv[0] = "-text"; argv[1] = new Path(root, "file.gz").toString(); int ret = ToolRunner.run(new FsShell(conf), argv); assertEquals("'-text " + argv[1] + " returned " + ret, 0, ret); assertTrue("Output doesn't match input", Arrays.equals(file.toByteArray(), out.toByteArray())); // Create a sequence file with a gz extension, to test proper // container detection. Magic detection. SequenceFile.Writer writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(new Path(root, "file.gz")), SequenceFile.Writer.keyClass(Text.class), SequenceFile.Writer.valueClass(Text.class)); writer.append(new Text("Foo"), new Text("Bar")); writer.close(); out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); argv = new String[2]; argv[0] = "-text"; argv[1] = new Path(root, "file.gz").toString(); ret = ToolRunner.run(new FsShell(conf), argv); assertEquals("'-text " + argv[1] + " returned " + ret, 0, ret); assertTrue("Output doesn't match input", Arrays.equals("Foo\tBar\n".getBytes(), out.toByteArray())); out.reset(); // Test deflate. Extension-based detection. OutputStream dout = new DeflaterOutputStream(fs.create(new Path(root, "file.deflate"))); byte[] outbytes = "foo".getBytes(); dout.write(outbytes); dout.close(); out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); argv = new String[2]; argv[0] = "-text"; argv[1] = new Path(root, "file.deflate").toString(); ret = ToolRunner.run(new FsShell(conf), argv); assertEquals("'-text " + argv[1] + " returned " + ret, 0, ret); assertTrue("Output doesn't match input", Arrays.equals(outbytes, out.toByteArray())); out.reset(); // Test a simple codec. Extension based detection. We use // Bzip2 cause its non-native. CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(BZip2Codec.class, conf); String extension = codec.getDefaultExtension(); Path p = new Path(root, "file." + extension); OutputStream fout = new DataOutputStream(codec.createOutputStream(fs.create(p, true))); byte[] writebytes = "foo".getBytes(); fout.write(writebytes); fout.close(); out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); argv = new String[2]; argv[0] = "-text"; argv[1] = new Path(root, p).toString(); ret = ToolRunner.run(new FsShell(conf), argv); assertEquals("'-text " + argv[1] + " returned " + ret, 0, ret); assertTrue("Output doesn't match input", Arrays.equals(writebytes, out.toByteArray())); out.reset(); } finally { if (null != bak) { System.setOut(bak); } } }
From source file:org.commoncrawl.util.ArcFileWriter.java
private String escapeURI(String uri, String charsetEncoding) throws IOException { boolean needToChange = false; StringBuffer out = new StringBuffer(uri.length()); Charset charset;/*from w w w. j a va 2 s .co m*/ CharArrayWriter charArrayWriter = new CharArrayWriter(); if (charsetEncoding == null) throw new NullPointerException("charsetName"); try { charset = Charset.forName(charsetEncoding); } catch (IllegalCharsetNameException e) { throw new UnsupportedEncodingException(charsetEncoding); } catch (UnsupportedCharsetException e) { throw new UnsupportedEncodingException(charsetEncoding); } for (int i = 0; i < uri.length();) { int c = (int) uri.charAt(i); // System.out.println("Examining character: " + c); if (dontNeedEncoding.get(c)) { out.append((char) c); i++; } else { // convert to external encoding before hex conversion do { charArrayWriter.write(c); /* * If this character represents the start of a Unicode surrogate pair, * then pass in two characters. It's not clear what should be done if * a bytes reserved in the surrogate pairs range occurs outside of a * legal surrogate pair. For now, just treat it as if it were any * other character. */ if (c >= 0xD800 && c <= 0xDBFF) { /* * System.out.println(Integer.toHexString(c) + * " is high surrogate"); */ if ((i + 1) < uri.length()) { int d = (int) uri.charAt(i + 1); /* * System.out.println("\tExamining " + Integer.toHexString(d)); */ if (d >= 0xDC00 && d <= 0xDFFF) { /* * System.out.println("\t" + Integer.toHexString(d) + * " is low surrogate"); */ charArrayWriter.write(d); i++; } } } i++; } while (i < uri.length() && !dontNeedEncoding.get((c = (int) uri.charAt(i)))); charArrayWriter.flush(); String str = new String(charArrayWriter.toCharArray()); byte[] ba = str.getBytes(charsetEncoding); for (int j = 0; j < ba.length; j++) { out.append('%'); char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16); // converting to use uppercase letter as part of // the hex value if ch is a letter. if (Character.isLetter(ch)) { ch -= caseDiff; } out.append(ch); ch = Character.forDigit(ba[j] & 0xF, 16); if (Character.isLetter(ch)) { ch -= caseDiff; } out.append(ch); } charArrayWriter.reset(); needToChange = true; } } return (needToChange ? out.toString() : uri); }
From source file:org.lwes.util.NumberCodec.java
/** * Turn an unsigned hex string into a long. This whole thing is here * to replace Long.parseLong(str,16) because it fails with large unsigned * hex strings (ones that denote negative values). When they work out * the signed hex vs. unsigned hex issue in the Java API, this can be * retired./*from ww w . j a v a 2 s .c om*/ * * @param str the String to parse * @return the long that was written in <code>str</code> */ private static long fromHexString(String str, long min) { final int hex = 16; final char firstChar = str.charAt(0); final int digit = Character.digit(firstChar, hex); if (digit < hex / 2) { return Long.parseLong(str, hex); } else { /* Subtract <code>hex/2</code> from the first digit and flip the sign. */ final String posStr = (Character.forDigit(digit - hex / 2, hex) + str.substring(1, str.length())); final long offsetLong = Long.parseLong(posStr, hex); return offsetLong + min; } }
From source file:org.signserver.module.pdfsigner.PDFSigner.java
protected byte[] addSignatureToPDFDocument(final ICryptoInstance crypto, PDFSignerParameters params, byte[] pdfbytes, byte[] password, int contentEstimated, final ProcessRequest request, final RequestContext context) throws IOException, DocumentException, CryptoTokenOfflineException, SignServerException, IllegalRequestException { // when given a content length (i.e. non-zero), it means we are running a second try boolean secondTry = contentEstimated != 0; // get signing cert certificate chain and private key final List<Certificate> certs = getSigningCertificateChain(crypto); if (certs == null) { throw new SignServerException("Null certificate chain. This signer needs a certificate."); }//from w w w .j a va2s. c o m final List<Certificate> includedCerts = includedCertificates(certs); Certificate[] certChain = includedCerts.toArray(new Certificate[includedCerts.size()]); PrivateKey privKey = crypto.getPrivateKey(); // need to check digest algorithms for DSA private key at signing // time since we can't be sure what key a configured alias selector gives back if (privKey instanceof DSAPrivateKey) { if (!"SHA1".equals(digestAlgorithm)) { throw new IllegalRequestException( "Only SHA1 is permitted as digest algorithm for DSA private keys"); } } PdfReader reader = new PdfReader(pdfbytes, password); boolean appendMode = true; // TODO: This could be good to have as a property in the future int pdfVersion; try { pdfVersion = Integer.parseInt(Character.toString(reader.getPdfVersion())); } catch (NumberFormatException e) { pdfVersion = 0; } if (LOG.isDebugEnabled()) { LOG.debug("PDF version: " + pdfVersion); } // Don't certify already certified documents if (reader.getCertificationLevel() != PdfSignatureAppearance.NOT_CERTIFIED && params.getCertification_level() != PdfSignatureAppearance.NOT_CERTIFIED) { throw new IllegalRequestException("Will not certify an already certified document"); } // Don't sign documents where the certification does not allow it if (reader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED || reader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_FORM_FILLING) { throw new IllegalRequestException("Will not sign a certified document where signing is not allowed"); } Permissions currentPermissions = Permissions.fromInt(reader.getPermissions()); if (params.getSetPermissions() != null && params.getRemovePermissions() != null) { throw new SignServerException("Signer " + workerId + " missconfigured. Only one of " + SET_PERMISSIONS + " and " + REMOVE_PERMISSIONS + " should be specified."); } Permissions newPermissions; if (params.getSetPermissions() != null) { newPermissions = params.getSetPermissions(); } else if (params.getRemovePermissions() != null) { newPermissions = currentPermissions.withRemoved(params.getRemovePermissions()); } else { newPermissions = null; } Permissions rejectPermissions = Permissions.fromSet(params.getRejectPermissions()); byte[] userPassword = reader.computeUserPassword(); int cryptoMode = reader.getCryptoMode(); if (LOG.isDebugEnabled()) { StringBuilder buff = new StringBuilder(); buff.append("Current permissions: ").append(currentPermissions).append("\n") .append("Remove permissions: ").append(params.getRemovePermissions()).append("\n") .append("Reject permissions: ").append(rejectPermissions).append("\n") .append("New permissions: ").append(newPermissions).append("\n").append("userPassword: ") .append(userPassword == null ? "null" : "yes").append("\n").append("ownerPassword: ") .append(password == null ? "no" : (isUserPassword(reader, password) ? "no" : "yes")) .append("\n").append("setOwnerPassword: ") .append(params.getSetOwnerPassword() == null ? "no" : "yes").append("\n").append("cryptoMode: ") .append(cryptoMode); LOG.debug(buff.toString()); } if (appendMode && (newPermissions != null || params.getSetOwnerPassword() != null)) { appendMode = false; if (LOG.isDebugEnabled()) { LOG.debug("Changing appendMode to false to be able to change permissions"); } } ByteArrayOutputStream fout = new ByteArrayOutputStream(); // increase PDF version if needed by digest algorithm final char updatedPdfVersion; if (minimumPdfVersion > pdfVersion) { updatedPdfVersion = Character.forDigit(minimumPdfVersion, 10); if (LOG.isDebugEnabled()) { LOG.debug("Need to upgrade PDF to version 1." + updatedPdfVersion); } // check that the document isn't already signed // when trying to upgrade version final AcroFields af = reader.getAcroFields(); final List<String> sigNames = af.getSignatureNames(); if (!sigNames.isEmpty()) { // TODO: in the future we might want to support // a fallback option in this case to allow re-signing using the same version (using append) throw new IllegalRequestException( "Can not upgrade an already signed PDF and a higher version is required to support the configured digest algorithm"); } appendMode = false; } else { updatedPdfVersion = '\0'; } PdfStamper stp = PdfStamper.createSignature(reader, fout, updatedPdfVersion, null, appendMode); PdfSignatureAppearance sap = stp.getSignatureAppearance(); // Set the new permissions if (newPermissions != null || params.getSetOwnerPassword() != null) { if (cryptoMode < 0) { cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128; if (LOG.isDebugEnabled()) { LOG.debug("Setting default encryption algorithm"); } } if (newPermissions == null) { newPermissions = currentPermissions; } if (params.getSetOwnerPassword() != null) { password = params.getSetOwnerPassword().getBytes("ISO-8859-1"); } else if (isUserPassword(reader, password)) { // We do not have an owner password so lets use a random one password = new byte[16]; random.nextBytes(password); if (LOG.isDebugEnabled()) { LOG.debug("Setting random owner password"); } } stp.setEncryption(userPassword, password, newPermissions.asInt(), cryptoMode); currentPermissions = newPermissions; } // Reject if any permissions are rejected and the document does not use a permission password // or if it contains any of the rejected permissions if (rejectPermissions.asInt() != 0) { if (cryptoMode < 0 || currentPermissions.containsAnyOf(rejectPermissions)) { throw new IllegalRequestException("Document contains permissions not allowed by this signer"); } } // include signer certificate crl inside cms package if requested CRL[] crlList = null; if (params.isEmbed_crl()) { crlList = getCrlsForChain(certs); } sap.setCrypto(null, certChain, crlList, PdfSignatureAppearance.SELF_SIGNED); // add visible signature if requested if (params.isAdd_visible_signature()) { int signaturePage = getPageNumberForSignature(reader, params); sap.setVisibleSignature(new com.lowagie.text.Rectangle(params.getVisible_sig_rectangle_llx(), params.getVisible_sig_rectangle_lly(), params.getVisible_sig_rectangle_urx(), params.getVisible_sig_rectangle_ury()), signaturePage, null); // set custom image if requested if (params.isUse_custom_image()) { sap.setAcro6Layers(true); PdfTemplate n2 = sap.getLayer(2); params.getCustom_image().setAbsolutePosition(0, 0); n2.addImage(params.getCustom_image()); } } // Certification level sap.setCertificationLevel(params.getCertification_level()); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.setReason(params.getReason()); dic.setLocation(params.getLocation()); dic.setDate(new PdfDate(Calendar.getInstance())); sap.setCryptoDictionary(dic); // add timestamp to signature if requested TSAClient tsc = null; if (params.isUse_timestamp()) { final String tsaUrl = params.getTsa_url(); if (tsaUrl != null) { tsc = getTimeStampClient(params.getTsa_url(), params.getTsa_username(), params.getTsa_password()); } else { tsc = new InternalTSAClient(getWorkerSession(), params.getTsa_worker(), params.getTsa_username(), params.getTsa_password()); } } // embed ocsp response in cms package if requested // for ocsp request to be formed there needs to be issuer certificate in // chain byte[] ocsp = null; if (params.isEmbed_ocsp_response() && certChain.length >= 2) { String url; try { url = PdfPKCS7.getOCSPURL((X509Certificate) certChain[0]); if (url != null && url.length() > 0) { ocsp = new OcspClientBouncyCastle((X509Certificate) certChain[0], (X509Certificate) certChain[1], url).getEncoded(); } } catch (CertificateParsingException e) { throw new SignServerException("Error getting OCSP URL from certificate", e); } } PdfPKCS7 sgn; try { sgn = new PdfPKCS7(privKey, certChain, crlList, digestAlgorithm, null, false); } catch (InvalidKeyException e) { throw new SignServerException("Error constructing PKCS7 package", e); } catch (NoSuchProviderException e) { throw new SignServerException("Error constructing PKCS7 package", e); } catch (NoSuchAlgorithmException e) { throw new SignServerException("Error constructing PKCS7 package", e); } MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance(digestAlgorithm); } catch (NoSuchAlgorithmException e) { throw new SignServerException("Error creating " + digestAlgorithm + " digest", e); } Calendar cal = Calendar.getInstance(); // calculate signature size if (contentEstimated == 0) { contentEstimated = calculateEstimatedSignatureSize(certChain, tsc, ocsp, crlList); } byte[] encodedSig = calculateSignature(sgn, contentEstimated, messageDigest, cal, params, certChain, tsc, ocsp, sap); if (LOG.isDebugEnabled()) { LOG.debug("Estimated size: " + contentEstimated); LOG.debug("Encoded length: " + encodedSig.length); } if (contentEstimated + 2 < encodedSig.length) { if (!secondTry) { int contentExact = encodedSig.length; LOG.warn( "Estimated signature size too small, usinging accurate calculation (resulting in an extra signature computation)."); if (LOG.isDebugEnabled()) { LOG.debug("Estimated size: " + contentEstimated + ", actual size: " + contentExact); } // try signing again return addSignatureToPDFDocument(crypto, params, pdfbytes, password, contentExact, request, context); } else { // if we fail to get an accurate signature size on the second attempt, bail out (this shouldn't happen) throw new SignServerException("Failed to calculate signature size"); } } byte[] paddedSig = new byte[contentEstimated]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); sap.close(dic2); reader.close(); fout.close(); return fout.toByteArray(); }
From source file:org.lockss.util.TestUrlUtil.java
String enc(int i, boolean upper) { StringBuffer sb = new StringBuffer(); sb.append("%"); sb.append(Character.forDigit((i >> 4) & 0xF, 16)); sb.append(Character.forDigit(i & 0xF, 16)); return upper ? sb.toString().toUpperCase() : sb.toString().toLowerCase(); }