public static void logTokens(Activity context) { // Add code to print out the key hash try { PackageInfo info = context .getPackageManager() .getPackageInfo( context.getApplicationContext().getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(signature.toByteArray()); Log.d("SHA-KeyHash:::", Base64.encodeToString(md.digest(), Base64.DEFAULT)); md = MessageDigest.getInstance("MD5"); md.update(signature.toByteArray()); Log.d("MD5-KeyHash:::", Base64.encodeToString(md.digest(), Base64.DEFAULT)); md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("SHA-Hex-From-KeyHash:::", bytesToHex(md.digest())); } } catch (NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { } }
public static String printKeyHash(Activity context) { PackageInfo packageInfo; String key = null; try { // getting application package name, as defined in manifest String packageName = context.getApplicationContext().getPackageName(); // Retriving package info packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES); Log.e("Package Name=", context.getApplicationContext().getPackageName()); for (Signature signature : packageInfo.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); key = new String(Base64.encode(md.digest(), 0)); // String key = new String(Base64.encodeBytes(md.digest())); Log.e("Key Hash=", key); } } catch (PackageManager.NameNotFoundException e1) { Log.e("Name not found", e1.toString()); } catch (NoSuchAlgorithmException e) { Log.e("No such an algorithm", e.toString()); } catch (Exception e) { Log.e("Exception", e.toString()); } return key; }
private String obfuscate(String data) { if (data == null || data.length() <= 0) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); // $NON-NLS-1$ } catch (NoSuchAlgorithmException ex) { try { digest = MessageDigest.getInstance("SHA"); // $NON-NLS-1$ } catch (NoSuchAlgorithmException ex1) { return "***"; //$NON-NLS-1$ } } digest.update(data.getBytes()); byte messageDigest[] = digest.digest(); StringBuilder hexString = new StringBuilder(64); 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); } return hexString.toString(); }
boolean isManifestUpdated() { if (!mCacheFile.exists()) { Log.i("ManifestCheckerService", "updated: cache file does not exist"); return true; } try { MessageDigest dataDigester = MessageDigest.getInstance("MD5"); dataDigester.update(mFetcher.getData(), 0, mFetcher.getDataLen()); byte[] dataDigest = dataDigester.digest(); MessageDigest fileDigester = MessageDigest.getInstance("MD5"); FileInputStream is = new FileInputStream(mCacheFile); byte[] buf = new byte[4096]; int len; while ((len = is.read(buf)) > 0) { fileDigester.update(buf, 0, len); } is.close(); byte[] fileDigest = fileDigester.digest(); if (Arrays.equals(dataDigest, fileDigest)) { return false; } Log.i("ManifestCheckerService", "updated: digests differ"); } catch (Exception e) { Log.e("ManifestFetcher", "caught exception: " + e.getMessage()); e.printStackTrace(); } return true; }
private MessageDigest setSHA1(AuthSecrets macParms) { try { mySHA1 = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { Trace.comm.errorm(" Unable to build SHA", e); Trace.comm.notifyFatal(); } MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { Trace.comm.errorm("Unable to build MD5", e); Trace.comm.notifyFatal(); } // Calculate the MAC key byte[] macKey = new byte[64]; System.arraycopy(md5Hash(0x11, macParms.myDHSecret, md5), 0, macKey, 0, 16); System.arraycopy(md5Hash(0x22, macParms.myDHSecret, md5), 0, macKey, 16, 16); System.arraycopy(md5Hash(0x33, macParms.myDHSecret, md5), 0, macKey, 32, 16); System.arraycopy(md5Hash(0x44, macParms.myDHSecret, md5), 0, macKey, 48, 16); myMACKey = macParms.myMacKey = macKey; // Set up to do the MAC calculation myIsDoingMac = true; myMAC = new byte[20]; return md5; }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest(request); String param = scr.getTheParameter("foo"); String bar = doSomething(param); java.security.Provider[] provider = java.security.Security.getProviders(); java.security.MessageDigest md; try { if (provider.length > 1) { md = java.security.MessageDigest.getInstance("SHA1", provider[0]); } else { md = java.security.MessageDigest.getInstance("SHA1", "SUN"); } } catch (java.security.NoSuchAlgorithmException e) { System.out.println( "Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.security.Provider)"); throw new ServletException(e); } catch (java.security.NoSuchProviderException e) { System.out.println( "Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.security.Provider)"); throw new ServletException(e); } response .getWriter() .println( "Hash Test java.security.MessageDigest.getInstance(java.lang.String,java.security.Provider) executed"); } // end doPost
/** * Initialise Secure layer of communications * * @param channels Virtual channels for this connection */ public Secure(VChannels channels) { this.channels = channels; McsLayer = new MCS(channels); Common.mcs = McsLayer; rc4_dec = new RC4(); rc4_enc = new RC4(); rc4_update = new RC4(); // sha1 = new SHA1(); // md5 = new MD5(); try { sha1 = MessageDigest.getInstance("SHA-1"); md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { e.printStackTrace(); } sec_sign_key = new byte[16]; // changed from 8 - rdesktop 1.2.0 sec_decrypt_key = new byte[16]; sec_encrypt_key = new byte[16]; sec_decrypt_update_key = new byte[16]; // changed from 8 - rdesktop // 1.2.0 sec_encrypt_update_key = new byte[16]; // changed from 8 - rdesktop // 1.2.0 sec_crypted_random = new byte[64]; }
/* goodG2B2() - use goodsource and badsink by reversing statements in first if */ private void goodG2B2() throws Throwable { String data; /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_final_t) { java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded string */ data = "foo"; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger log_bad = Logger.getLogger("local-logger"); data = ""; /* init data */ /* read user input from console with readLine*/ BufferedReader buffread = null; InputStreamReader instrread = null; try { instrread = new InputStreamReader(System.in); buffread = new BufferedReader(instrread); data = buffread.readLine(); } catch (IOException ioe) { log_bad.warning("Error with stream reading"); } finally { /* clean up stream reading objects */ try { if (buffread != null) { buffread.close(); } } catch (IOException ioe) { log_bad.warning("Error closing buffread"); } finally { try { if (instrread != null) { instrread.close(); } } catch (IOException ioe) { log_bad.warning("Error closing instrread"); } } } } /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_final_t) { MessageDigest hash = MessageDigest.getInstance("SHA-512"); hash.update(data.getBytes()); /* FLAW: SHA512 with a predictable salt */ byte[] hashv = hash.digest("hash me".getBytes()); IO.writeLine(IO.toHex(hashv)); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ SecureRandom r = new SecureRandom(); MessageDigest hash = MessageDigest.getInstance("SHA-512"); hash.update(r.getSeed(32)); /* FIX: Use a sufficiently random salt */ byte[] hashv = hash.digest("hash me".getBytes()); IO.writeLine(IO.toHex(hashv)); } }
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); }
public static FileDesc loadFile(Path root, Path file, int blocSize) throws NoSuchAlgorithmException, FileNotFoundException, IOException { MessageDigest md = MessageDigest.getInstance("SHA-512"); MessageDigest fileMd = MessageDigest.getInstance("SHA-512"); FileDesc desc = new FileDesc(file.toString(), null, null); List<Bloc> list = new ArrayList<Bloc>(); try (FileInputStream fis = new FileInputStream(root.resolve(file).toString())) { byte[] buf = new byte[blocSize]; byte[] h; int s; while ((s = fis.read(buf)) != -1) { int c; while (s < buf.length && (c = fis.read()) != -1) buf[s++] = (byte) c; fileMd.update(buf, 0, s); // padding byte p = 0; while (s < buf.length) buf[s++] = ++p; h = md.digest(buf); Bloc bloc = new Bloc(RollingChecksum.compute(buf), new Hash(h)); list.add(bloc); } h = fileMd.digest(); desc.fileHash = new Hash(h); desc.blocs = list.toArray(new Bloc[0]); } return desc; }
private void addVersion(HashBlock block, String content) throws Exception { // 1 plain hash, plus 4 voters MessageDigest[] digests = new MessageDigest[5]; // fake "Plain Hash" digests[0] = MessageDigest.getInstance("SHA1"); digests[0].update(content.getBytes()); // fake "Nonced Hash" for voter 1 digests[1] = MessageDigest.getInstance("SHA1"); digests[1].update(content.getBytes()); // fake "Nonced Hash" for voter 2 digests[2] = MessageDigest.getInstance("SHA1"); digests[2].update(content.getBytes()); // fake "Nonced Hash" for voter 3 digests[3] = MessageDigest.getInstance("SHA1"); digests[3].update(content.getBytes()); // fake "Nonced Hash" for voter 4 digests[4] = MessageDigest.getInstance("SHA1"); digests[4].update(content.getBytes()); block.addVersion( 0, content.length(), 0, content.length(), digests.length * content.length(), // total bytes hashed digests, hbVersionNum++, null); }
@Override protected HashMap<String, String> doInBackground(File... params) { HashMap<String, String> digest = new HashMap<String, String>(); File file = params[0]; MessageDigest md5 = null; MessageDigest sha1 = null; CRC32 crc32 = null; InputStream is = null; try { md5 = MessageDigest.getInstance("MD5"); sha1 = MessageDigest.getInstance("SHA1"); crc32 = new CRC32(); is = new FileInputStream(file); int count = 0; byte buffer[] = new byte[24 * 1024]; while ((count = is.read(buffer)) > 0) { md5.update(buffer, 0, count); sha1.update(buffer, 0, count); crc32.update(buffer, 0, count); } StringBuilder md5Builder = new StringBuilder(); for (byte b : md5.digest()) { String hex = Integer.toHexString(0xFF & b); if (hex.length() == 2) md5Builder.append(hex); else md5Builder.append("0" + hex); logger.debug(hex); } digest.put("MD5", md5Builder.toString()); StringBuilder sha1Builder = new StringBuilder(); for (byte b : sha1.digest()) { String hex = Integer.toHexString(0xFF & b); if (hex.length() == 2) sha1Builder.append(hex); else sha1Builder.append("0" + hex); logger.debug(hex); } digest.put("SHA1", sha1Builder.toString()); digest.put("CRC", Long.toString(crc32.getValue())); return digest; } catch (Exception e) { digest.put("MD5", "Unable to read md5sum."); digest.put("SHA1", "Unable to read sha1sum."); digest.put("CRC", "Unable to read sha1sum."); return digest; } finally { try { is.close(); } catch (Exception e) { } } }
@Before public void initValue() { try { mt = MD5Tool.getInstance(); md = MessageDigest.getInstance("md5"); sd = MessageDigest.getInstance("sha1"); } catch (Exception e) { e.printStackTrace(); } }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest(request); String param = scr.getTheParameter("foo"); String bar; String guess = "ABC"; char switchTarget = guess.charAt(2); // Simple case statement that assigns param to bar on conditions 'A' or 'C' switch (switchTarget) { case 'A': bar = param; break; case 'B': bar = "bobs_your_uncle"; break; case 'C': case 'D': bar = param; break; default: bar = "bobs_your_uncle"; break; } java.security.Provider[] provider = java.security.Security.getProviders(); java.security.MessageDigest md; try { if (provider.length > 1) { md = java.security.MessageDigest.getInstance("sha-384", provider[0]); } else { md = java.security.MessageDigest.getInstance("sha-384", "SUN"); } } catch (java.security.NoSuchAlgorithmException e) { System.out.println( "Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.security.Provider)"); throw new ServletException(e); } catch (java.security.NoSuchProviderException e) { System.out.println( "Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.security.Provider)"); throw new ServletException(e); } response .getWriter() .println( "Hash Test java.security.MessageDigest.getInstance(java.lang.String,java.security.Provider) executed"); }
/* goodG2B2() - use goodsource and badsink by reversing statements in first if */ private void goodG2B2() throws Throwable { String data; /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_final_five == 5) { java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded string */ data = "foo"; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger log_bad = Logger.getLogger("local-logger"); data = ""; /* init data */ /* retrieve the property */ Properties props = new Properties(); FileInputStream finstr = null; try { finstr = new FileInputStream("../common/config.properties"); props.load(finstr); data = props.getProperty("data"); } catch (IOException ioe) { log_bad.warning("Error with stream reading"); } finally { /* clean up stream reading objects */ try { if (finstr != null) { finstr.close(); } } catch (IOException ioe) { log_bad.warning("Error closing buffread"); } } } /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_final_five == 5) { MessageDigest hash = MessageDigest.getInstance("SHA-512"); hash.update(data.getBytes()); /* FLAW: SHA512 with a predictable salt */ byte[] hashv = hash.digest("hash me".getBytes()); IO.writeLine(IO.toHex(hashv)); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ SecureRandom r = new SecureRandom(); MessageDigest hash = MessageDigest.getInstance("SHA-512"); hash.update(r.getSeed(32)); /* FIX: Use a sufficiently random salt */ byte[] hashv = hash.digest("hash me".getBytes()); IO.writeLine(IO.toHex(hashv)); } }
public SimpleDigest() { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ne) { digest = null; hash = 13; } } }
static { try { md5digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException("no MD5 digester", ex); } try { sha1digest = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException("no SHA1 digester", ex); } }
/** Tests SHA MessageDigest provider */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "", method = "getInstance", args = {java.lang.String.class}) public void testSHAProvider() { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { fail("unexpected exception: " + e); } byte[] bytes = new byte[] {1, 1, 1, 1, 1}; // Regression for HARMONY-1120 // testing combination with provider try { // offset < 0 md.update(bytes, -1, 1); fail("No expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } // No exception for len < 0 md.update(bytes, 1, -1); // Regression for Harmony-1148 try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { fail("unexpected exception: " + e); } try { // offset < 0 md.digest(bytes, 0, -1); fail("No expected DigestException"); } catch (DigestException e) { } try { // len < 0 md.digest(bytes, -1, 0); fail("No expected DigestException"); } catch (DigestException e) { } try { md = MessageDigest.getInstance("UnknownDigest"); fail("expected NoSuchAlgorithmException"); } catch (NoSuchAlgorithmException e) { // ok } }
static MessageDigest createDigestInstance(String digestAlgOID, Provider provider) throws NoSuchAlgorithmException { String digestName = TSPUtil.getDigestAlgName(digestAlgOID); if (provider != null) { try { return MessageDigest.getInstance(digestName, provider); } catch (NoSuchAlgorithmException e) { // Ignore } } return MessageDigest.getInstance(digestName); }
private FSOutputStream( FSRevisionNode revNode, CountingOutputStream targetFileOS, File targetFile, InputStream source, long deltaStart, long repSize, long repOffset, FSTransactionRoot txnRoot, boolean compress, FSWriteLock txnLock) throws SVNException { myTxnRoot = txnRoot; myTargetFileOS = targetFileOS; myTargetFile = targetFile; mySourceStream = source; myDeltaStart = deltaStart; myRepSize = repSize; myRepOffset = repOffset; isHeaderWritten = false; myRevNode = revNode; mySourceOffset = 0; myIsClosed = false; myTxnLock = txnLock; myDeltaGenerator = new SVNDeltaGenerator(SVN_DELTA_WINDOW_SIZE); myTextBuffer = new ByteArrayOutputStream(); try { myMD5Digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { SVNErrorMessage err = SVNErrorMessage.create( SVNErrorCode.IO_ERROR, "MD5 implementation not found: {0}", nsae.getLocalizedMessage()); SVNErrorManager.error(err, nsae, SVNLogType.FSFS); } try { mySHA1Digest = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException nsae) { SVNErrorMessage err = SVNErrorMessage.create( SVNErrorCode.IO_ERROR, "SHA1 implementation not found: {0}", nsae.getLocalizedMessage()); SVNErrorManager.error(err, nsae, SVNLogType.FSFS); } myIsCompress = compress; }
/** * Initialize the encryption system * * @param type - {@link Algorithm} to be used(e.g: MD5, SHA, ...) */ public Encrypter(Algorithm type) throws NoSuchAlgorithmException { log.debug("Initializing the encrypter"); setType(type); try { digest = MessageDigest.getInstance(type.algorithm()); } catch (NoSuchAlgorithmException e) { log.warn( "The " + type.algorithm() + " algorithm is not available on current system...setting a default type - " + defaultType.algorithm(), e); digest = MessageDigest.getInstance(defaultType.algorithm()); } }
/** * * Login to the POP3 server with the given username and authentication information. Use this * method when connecting to a server requiring authentication using the APOP command. Because the * timestamp produced in the greeting banner varies from server to server, it is not possible to * consistently extract the information. Therefore, after connecting to the server, you must call * {@link org.apache.commons.net.pop3.POP3#getReplyString getReplyString } and parse out the * timestamp information yourself. * * <p>You must first connect to the server with {@link org.apache.commons.net.SocketClient#connect * connect } before attempting to login. A login attempt is only valid if the client is in the * {@link org.apache.commons.net.pop3.POP3#AUTHORIZATION_STATE AUTHORIZATION_STATE } . After * logging in, the client enters the {@link org.apache.commons.net.pop3.POP3#TRANSACTION_STATE * TRANSACTION_STATE } . After connecting, you must parse out the server specific information to * use as a timestamp, and pass that information to this method. The secret is a shared secret * known to you and the server. See RFC 1939 for more details regarding the APOP command. * * <p> * * @param username The account name being logged in to. * @param timestamp The timestamp string to combine with the secret. * @param secret The shared secret which produces the MD5 digest when combined with the timestamp. * @return True if the login attempt was successful, false if not. * @exception IOException If a network I/O error occurs in the process of logging in. * @exception NoSuchAlgorithmException If the MD5 encryption algorithm cannot be instantiated by * the Java runtime system. * */ public boolean login(String username, String timestamp, String secret) throws IOException, NoSuchAlgorithmException { int i; byte[] digest; StringBuffer buffer, digestBuffer; MessageDigest md5; if (getState() != AUTHORIZATION_STATE) return false; md5 = MessageDigest.getInstance("MD5"); timestamp += secret; digest = md5.digest(timestamp.getBytes()); digestBuffer = new StringBuffer(128); for (i = 0; i < digest.length; i++) digestBuffer.append(Integer.toHexString(digest[i] & 0xff)); buffer = new StringBuffer(256); buffer.append(username); buffer.append(' '); buffer.append(digestBuffer.toString()); if (sendCommand(POP3Command.APOP, buffer.toString()) != POP3Reply.OK) return false; setState(TRANSACTION_STATE); return true; }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getParameter("foo"); java.util.List<String> valuesList = new java.util.ArrayList<String>(); valuesList.add("safe"); valuesList.add(param); valuesList.add("moresafe"); valuesList.remove(0); // remove the 1st safe value String bar = valuesList.get(0); // get the param value try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-512", "SUN"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println( "Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.lang.String)"); throw new ServletException(e); } catch (java.security.NoSuchProviderException e) { System.out.println( "Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.lang.String)"); throw new ServletException(e); } response .getWriter() .println( "Hash Test java.security.MessageDigest.getInstance(java.lang.String,java.lang.String) executed"); }
// MD5加密,32位 public static String MD5(String str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { e.printStackTrace(); return ""; } char[] charArray = str.toCharArray(); byte[] byteArray = new byte[charArray.length]; for (int i = 0; i < charArray.length; i++) { byteArray[i] = (byte) charArray[i]; } byte[] md5Bytes = md5.digest(byteArray); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < md5Bytes.length; i++) { int val = ((int) md5Bytes[i]) & 0xff; if (val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); }
public static boolean isAuthenticated(String username, String connectionHash, SecretKey shared) throws NoSuchAlgorithmException, IOException { String encName = URLEncoder.encode(username, "UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-1"); for (byte[] bit : new byte[][] { connectionHash.getBytes("ISO_8859_1"), shared.getEncoded(), keys.getPublic().getEncoded() }) { sha.update(bit); } String encodedHash = URLEncoder.encode(new BigInteger(sha.digest()).toString(16), "UTF-8"); String authURL = "http://session.minecraft.net/game/checkserver.jsp?user="******"&serverId=" + encodedHash; String reply; try (BufferedReader in = new BufferedReader(new InputStreamReader(new URL(authURL).openStream()))) { reply = in.readLine(); } return "YES".equals(reply); }
public static String md5(String plainText) { String str; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } str = buf.toString(); // System.out.println("result: " + buf.toString());// 32位的加密 // System.out.println("result: " + buf.toString().substring(8, // 24));// 16位的加密 return str; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
public PdfEncryption() { try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new ExceptionConverter(e); } }
private FSInputStream(SVNDeltaCombiner combiner, FSRepresentation representation, FSFS owner) throws SVNException { myCombiner = combiner; myChunkIndex = 0; isChecksumFinalized = false; myHexChecksum = representation.getMD5HexDigest(); myOffset = 0; myLength = representation.getExpandedSize(); try { myDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { SVNErrorMessage err = SVNErrorMessage.create( SVNErrorCode.IO_ERROR, "MD5 implementation not found: {0}", nsae.getLocalizedMessage()); SVNErrorManager.error(err, nsae, SVNLogType.FSFS); } try { buildRepresentationList(representation, myRepStateList, owner); } catch (SVNException svne) { /* * Something terrible has happened while building rep list, need to * close any files still opened */ close(); throw svne; } }
static { try { digest_ = new SafeMessageDigest(MessageDigest.getInstance("SHA-1")); } catch (NoSuchAlgorithmException e) { assert (false); } }
/** * Returns a <code>MessageDigest</code> for the given <code>algorithm</code>. * * @param algorithm the name of the algorithm requested. See <a * href="http://java.sun.com/j2se/1.3/docs/guide/security/CryptoSpec.html#AppA">Appendix A in * the Java Cryptography Architecture API Specification & Reference</a> for information about * standard algorithm names. * @return An MD5 digest instance. * @see MessageDigest#getInstance(String) * @throws IllegalArgumentException when a {@link NoSuchAlgorithmException} is caught. */ public static MessageDigest getDigest(String algorithm) { try { return MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } }