public static String getCryptUrl(String paramString) { StringBuffer localStringBuffer = new StringBuffer(paramString); if (paramString.indexOf("?") == -1) { localStringBuffer.append("?"); } else { localStringBuffer.append("&"); } localStringBuffer.append("cyt=1"); return localStringBuffer.toString(); }
/** Transform the specified byte into a Hex String form. */ public static final String bytesToHexStr(byte[] bcd) { StringBuffer s = new StringBuffer(bcd.length * 2); for (int i = 0; i < bcd.length; i++) { s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]); s.append(bcdLookup[bcd[i] & 0x0f]); } return s.toString(); }
/* Cert RQ info header */ private String buildRequestInfoHeader(String subject) { StringBuffer buff = new StringBuffer( "This is a Certificate Request file:\nIt should be mailed to to a CA for signature"); buff.append("\n==============================================================="); buff.append("\nCertificate Subject:\n\t"); buff.append(subject); buff.append("\n\n"); return buff.toString(); }
/** Return string representation of this VMID. */ public String toString() { StringBuffer result = new StringBuffer(); if (addr != null) for (int i = 0; i < addr.length; ++i) { int x = (int) (addr[i] & 0xFF); result.append((x < 0x10 ? "0" : "") + Integer.toString(x, 16)); } result.append(':'); result.append(uid.toString()); return result.toString(); }
public ManifestDigester(byte bytes[]) { rawBytes = bytes; entries = new HashMap(); // first skip the main attributes Position pos = new Position(); if (!findSection(0, pos)) return; // exception? int start = pos.startOfNext; while (findSection(start, pos)) { int len = pos.endOfFirstLine - start + 1; int sectionLen = pos.endOfSection - start + 1; int sectionLenWithBlank = pos.startOfNext - start; if (len > 6) { if (isNameAttr(bytes, start)) { StringBuffer nameBuf = new StringBuffer(); nameBuf.append(new String(bytes, start + 6, len - 6)); int i = start + len; if ((i - start) < sectionLen) { if (bytes[i] == '\r') { i += 2; } else { i += 1; } } while ((i - start) < sectionLen) { if (bytes[i++] == ' ') { // name is wrapped int wrapStart = i; while (((i - start) < sectionLen) && (bytes[i++] != '\n')) ; if (bytes[i - 1] != '\n') return; // exception? int wrapLen; if (bytes[i - 2] == '\r') wrapLen = i - wrapStart - 2; else wrapLen = i - wrapStart - 1; nameBuf.append(new String(bytes, wrapStart, wrapLen)); } else { break; } } String name = nameBuf.toString(); entries.put(name, new Entry(start, sectionLen, sectionLenWithBlank, rawBytes)); } } start = pos.startOfNext; } }
/** * Converts the given byte data into Hex string. * * @param data the byte array to convert * @return the Hex string representation of the given byte array */ private static String convertToHex(byte[] data) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); }
public static String getJavaStringLiteral(String text) { StringBuffer buf = new StringBuffer(); buf.append('"'); int len = text.length(); for (int i = 0; i < len; i++) { char ch = text.charAt(i); switch (ch) { case '\\': buf.append("\\\\"); break; case '\n': buf.append("\\n"); break; case '\r': buf.append("\\r"); break; case '\t': buf.append("\\t"); break; case '"': buf.append("\\\""); break; default: buf.append(ch); break; } } buf.append('"'); return buf.toString(); }
static int appendMethodSignature(Class[] argTypes, Class returnType, StringBuffer sb) { sb.append('('); int firstLocal = 1 + argTypes.length; // includes this. for (int i = 0; i < argTypes.length; i++) { Class type = argTypes[i]; appendTypeString(sb, type); if (type == Long.TYPE || type == Double.TYPE) { // adjust for duble slot ++firstLocal; } } sb.append(')'); appendTypeString(sb, returnType); return firstLocal; }
public static String toString(byte[] b) { if (b == null) { return "(null)"; } StringBuffer sb = new StringBuffer(b.length * 3); for (int i = 0; i < b.length; i++) { int k = b[i] & 0xff; if (i != 0) { sb.append(':'); } sb.append(hexDigits[k >>> 4]); sb.append(hexDigits[k & 0xf]); } return sb.toString(); }
public static String getJavaIdentifier(String candidateID) { int len = candidateID.length(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < len; i++) { char ch = candidateID.charAt(i); boolean good = i == 0 ? Character.isJavaIdentifierStart(ch) : Character.isJavaIdentifierPart(ch); if (good) { buf.append(ch); } else { buf.append('_'); } } return buf.toString(); }
/* * Utility method that converts a <code>URL[]</code> into a corresponding, * space-separated string with the same array elements. Note that if the * array has zero elements, the return value is null, not the empty string. */ private static String urlsToPath(URL[] urls) { // TODO - check if spaces in file paths are properly escaped (i.e.% // chars) if (urls.length == 0) { return null; } else if (urls.length == 1) { return urls[0].toExternalForm(); } else { StringBuffer path = new StringBuffer(urls[0].toExternalForm()); for (int i = 1; i < urls.length; i++) { path.append(' '); path.append(urls[i].toExternalForm()); } return path.toString(); } }
public static String hex(byte[] array) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); }
private static String convertToHex(byte[] arrayBytes) { StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < arrayBytes.length; i++) { stringBuffer.append(Integer.toString((arrayBytes[i] & 0xff) + 0x100, 16).substring(1)); } return stringBuffer.toString(); }
String[] getMedkit( String[] availableResources, String[] requiredResources, String[] missions, double P, double C) { try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(exec); OutputStream os = proc.getOutputStream(); InputStream is = proc.getInputStream(); new ErrorReader(proc.getErrorStream()).start(); StringBuffer sb = new StringBuffer(); append(sb, availableResources); append(sb, requiredResources); append(sb, missions); sb.append(P).append('\n'); sb.append(C).append('\n'); os.write(sb.toString().getBytes()); BufferedReader br = new BufferedReader(new InputStreamReader(is)); int N = Integer.parseInt(br.readLine().trim()); String[] ret = new String[N]; for (int i = 0; i < N; i++) ret[i] = br.readLine().trim(); return ret; } catch (Exception e) { System.err.println("An error occurred while executing your program"); e.printStackTrace(); return null; } }
public static String[] split(String phrase) { int length = phrase.length(); ArrayList wordList = new ArrayList(); StringBuffer word = null; for (int i = 0; i < length; i++) { char ch = phrase.charAt(i); switch (ch) { case ' ': case '\t': case '\r': case '\n': if (word != null) { wordList.add(word.toString()); word = null; } break; default: if (word == null) { word = new StringBuffer(); } word.append(ch); } } if (word != null) { wordList.add(word.toString()); } return (String[]) wordList.toArray(EMPTY_ARRAY); }
/** * @param s * @return */ public static String mask(final String s) { final StringBuffer buffer = new StringBuffer(25); final int count = (s != null ? s.length() : 0); for (int n = 0; n < count; n++) { buffer.append('*'); } return buffer.toString(); }
/** * 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[] hexStr2ByteArr(String * strIn) 互为可逆的转换过程 * * @param arrB 需要转换的byte数组 * @return 转换后的字符串 * @throws Exception 本方法不处理任何异常,所有异常全部抛出 */ public static String byteArr2HexStr(byte[] arrB) { int iLen = arrB.length; // 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍 StringBuffer sb = new StringBuffer(iLen * 2); for (int i = 0; i < iLen; i++) { int intTmp = arrB[i]; // 把负数转换为正数 while (intTmp < 0) { intTmp = intTmp + 256; } // 小于0F的数需要在前面补0 if (intTmp < 16) { sb.append("0"); } sb.append(Integer.toString(intTmp, 16)); } return sb.toString(); }
public String getClassPath() { StringBuffer cpath = new StringBuffer(); String sep = System.getProperty("path.separator"); for (int i = 0; i < jars.size(); i++) { cpath.append((String) jars.elementAt(i) + sep); } return cpath.toString(); }
public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getName()); sb.append('@'); sb.append(Integer.toHexString(System.identityHashCode(this))); sb.append(" (context="); sb.append(_context); sb.append(", static_permitions="); sb.append(_statisPermissions); sb.append(')'); return sb.toString(); }
/** Write certficate bytes into a PEM encoded string */ public static String writePEM(byte[] bytes, String hdr, String ftr) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Base64OutputStream b64os = new Base64OutputStream(bos); b64os.write(bytes); b64os.flush(); b64os.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); InputStreamReader irr = new InputStreamReader(bis); BufferedReader r = new BufferedReader(irr); StringBuffer buff = new StringBuffer(); String line; buff.append(hdr); while ((line = r.readLine()) != null) { buff.append(line + "\n"); } buff.append(ftr); return buff.toString(); }
/** * Computing the hash for a method is useful so as to create an alternate key from the method name * + signature. * * @param qualifiedMethodName * @param methodSignature * @return */ public static String computeHash(String qualifiedMethodName, String methodSignature) { String fullMethodName = qualifiedMethodName + methodSignature; byte[] bytes = fullMethodName.getBytes(); md5.reset(); md5.update(bytes); byte[] messageBytes = md5.digest(); StringBuffer message = new StringBuffer(); for (byte aByte : messageBytes) { String expanded = Integer.toHexString(0xFF & aByte); if (expanded.length() == 1) { // normalize length of all strings message.append("0"); } message.append(expanded); } return message.toString(); }
public static String Go(String rsa_len) throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(Integer.valueOf(rsa_len)); byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded(); StringBuffer retString = new StringBuffer(); for (int i = 0; i < publicKey.length; ++i) { retString.append(Integer.toHexString(0x0100 + (publicKey[i] & 0x00FF)).substring(1)); } return retString.toString(); }
private static StringBuffer appendTypeString(StringBuffer sb, Class type) { while (type.isArray()) { sb.append('['); type = type.getComponentType(); } if (type.isPrimitive()) { char typeLetter; if (type == Boolean.TYPE) { typeLetter = 'Z'; } else if (type == Long.TYPE) { typeLetter = 'J'; } else { String typeName = type.getName(); typeLetter = Character.toUpperCase(typeName.charAt(0)); } sb.append(typeLetter); } else { sb.append('L'); sb.append(type.getName().replace('.', '/')); sb.append(';'); } return sb; }
public static String md5(String unhashed) { String hashed = ""; byte[] defaultBytes = unhashed.getBytes(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(defaultBytes); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } hashed = hexString.toString(); // messageDigest.toString(); } catch (NoSuchAlgorithmException nsae) { } return hashed; }
public static void main(String[] args) throws Exception { // // verifica args e recebe o texto plano if (args.length != 1) { System.err.println("Usage: java DigitalSignatureExample text"); System.exit(1); } byte[] plainText = args[0].getBytes("UTF8"); // // gera o par de chaves RSA System.out.println("\nStart generating RSA key"); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair key = keyGen.generateKeyPair(); System.out.println("Finish generating RSA key"); // // define um objeto signature para utilizar MD5 e RSA // e assina o texto plano com a chave privada, // o provider utilizado tambem eh impresso Signature sig = Signature.getInstance("MD5WithRSA"); sig.initSign(key.getPrivate()); sig.update(plainText); byte[] signature = sig.sign(); System.out.println(sig.getProvider().getInfo()); System.out.println("\nSignature:"); // converte o signature para hexadecimal StringBuffer buf = new StringBuffer(); for (int i = 0; i < signature.length; i++) { String hex = Integer.toHexString(0x0100 + (signature[i] & 0x00FF)).substring(1); buf.append((hex.length() < 2 ? "0" : "") + hex); } // imprime o signature em hexadecimal System.out.println(buf.toString()); // // verifica a assinatura com a chave publica System.out.println("\nStart signature verification"); sig.initVerify(key.getPublic()); sig.update(plainText); try { if (sig.verify(signature)) { System.out.println("Signature verified"); } else System.out.println("Signature failed"); } catch (SignatureException se) { System.out.println("Singature failed"); } }
// Other Functions public static String encrypt(String pass) { // Encrypts password using MD5 try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] passBytes = pass.getBytes(); md.reset(); byte[] digested = md.digest(passBytes); StringBuffer sb = new StringBuffer(); for (int i = 0; i < digested.length; i++) { sb.append(Integer.toHexString(0xff & digested[i])); } return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
/* * Initializes the signerInfo and the VerifierInfo from the Certificate Pair */ private void initializeCertificates() { X509Certificate certRoot = null; X509Certificate certIssuer = null; CertificatePair trustedCertificate; if (getFoundCertificate() == null) { CertificatePair[] certs = getRootCertificates(); if (certs.length == 0) return; trustedCertificate = certs[0]; } else { trustedCertificate = getFoundCertificate(); } certRoot = (X509Certificate) trustedCertificate.getRoot(); certIssuer = (X509Certificate) trustedCertificate.getIssuer(); StringBuffer strb = new StringBuffer(); strb.append(issuerString(certIssuer.getSubjectDN())); strb.append("\r\n"); // $NON-NLS-1$ strb.append( NLS.bind( Messages.JarVerificationResult_ValidBetween, (new String[] { dateString(certIssuer.getNotBefore()), dateString(certIssuer.getNotAfter()) }))); strb.append(checkValidity(certIssuer)); signerInfo = strb.toString(); if (certIssuer != null && !certIssuer.equals(certRoot)) { strb = new StringBuffer(); strb.append(issuerString(certIssuer.getIssuerDN())); strb.append("\r\n"); // $NON-NLS-1$ strb.append( NLS.bind( Messages.JarVerificationResult_ValidBetween, (new String[] { dateString(certRoot.getNotBefore()), dateString(certRoot.getNotAfter()) }))); strb.append(checkValidity(certRoot)); verifierInfo = strb.toString(); } }
/** * readPEM: Read a PEM encoded base64 stream and decode it * * @param is Base64 PEM encoded stream * @param hdr Header delimeter (e.g. ----------CERTIFICATE---------) * @param ftr Footer delimeter (e.g. ----------END CERTIFICATE---------) * @return decoded DER bytes * @throws IOException if a read error occurs */ public static byte[] readPEM(InputStream is, String hdr, String ftr) throws IOException { logger.debug("Reading PEM hdr:" + hdr + " ftr:" + ftr); is.reset(); InputStreamReader irr = new InputStreamReader(is); BufferedReader r = new BufferedReader(irr); StringBuffer buff = new StringBuffer(); String line; boolean read = false; while ((line = r.readLine()) != null) { if (line.equals(hdr)) { read = true; continue; } if (line.equals(ftr)) read = false; if (read) buff.append(line); } return Base64.decode(buff.toString().getBytes()); }
// encode password using md5 private String encodePassword(String pass) { byte[] bytesOfMessage; String unencodedpass = md5salt + pass; String encodedpass = ""; try { bytesOfMessage = unencodedpass.getBytes("UTF-8"); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digest = md.digest(bytesOfMessage); StringBuffer sb = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { sb.append(Integer.toHexString((digest[i] & 0xFF) | 0x100).substring(1, 3)); } encodedpass = sb.toString(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return encodedpass; }
/** Returns the URL for the request */ public StringBuffer getRequestURL() { StringBuffer sb = new StringBuffer(); sb.append(getScheme()); sb.append("://"); sb.append(getServerName()); int port = getServerPort(); if (port > 0 && port != 80 && port != 443) { sb.append(":"); sb.append(port); } sb.append(getRequestURI()); return sb; }