Java Code Examples for java.security.NoSuchAlgorithmException

The following are top voted examples for showing how to use java.security.NoSuchAlgorithmException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: OsmUi   File: mxUtils.java View source code Vote up 6 votes
/**
 * Returns the Md5 hash for the given text.
 * 
 * @param text
 *            String whose Md5 hash should be returned.
 * @return Returns the Md5 hash for the given text.
 */
public static String getMd5Hash(String text)
{
	StringBuffer result = new StringBuffer(32);
	try
	{
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(text.getBytes());
		Formatter f = new Formatter(result);

		byte[] digest = md5.digest();

		for (int i = 0; i < digest.length; i++)
		{
			f.format("%02x", new Object[] { new Byte(digest[i]) });
		}
	}
	catch (NoSuchAlgorithmException ex)
	{
		ex.printStackTrace();
	}

	return result.toString();
}
 
Example 2
Project: jena   File: NodeLib.java View source code Vote up 6 votes
private static MessageDigest allocDigest()
{
    try {
        MessageDigest disgest = digesters.get() ;
        if ( disgest == null ) 
            disgest = MessageDigest.getInstance("MD5");
        return disgest ;
    }
    catch (NoSuchAlgorithmException e)
    { e.printStackTrace(); return null ; }
}
 
Example 3
Project: TrustedIntents   File: ApkSignaturePin.java View source code Vote up 6 votes
/**
 * Gets the fingerprint of the first certificate in the signature.
 *
 * @param algorithm - Which hash to use (e.g. MD5, SHA1, SHA-256)
 * @return the fingerprint as hex String
 */
public String getFingerprint(String algorithm) {
    try {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        byte[] hashBytes = md.digest(certificates[0]);
        BigInteger bi = new BigInteger(1, hashBytes);
        md.reset();
        return String.format("%0" + (hashBytes.length << 1) + "x", bi);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 4
Project: Todayinformation   File: MD5Utils.java View source code Vote up 6 votes
public static String md5(String str){
	
	MessageDigest md;
	try {
		md = MessageDigest.getInstance("MD5");
		md.update(str.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));
			
		}
		
		return buf.toString();
		
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
	
	return str;
}
 
Example 5
Project: encontreaquipecas   File: Util.java View source code Vote up 6 votes
public static String MD5(String texto) {
    String sen = "";
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");
        BigInteger hash = new BigInteger(1, md.digest(texto.getBytes()));
        sen = hash.toString(16);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }        
    return sen;
}
 
Example 6
Project: SampleCSipSimpleApp   File: PopupMainActivity.java View source code Vote up 6 votes
public static String md5(String s) {
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < messageDigest.length; i++)
            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
        return hexString.toString();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 7
Project: ZoteroDroid   File: Md5Hash.java View source code Vote up 6 votes
public static String md5(String s){
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();
        
        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        for (int i=0; i<messageDigest.length; i++)
            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
        return hexString.toString();
        
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 8
Project: BambooPlayer   File: MD5Util.java View source code Vote up 6 votes
public static String MD5(String plainText ) {
StringBuffer buf = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte b[] = md.digest();
int i;
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));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return buf.toString();
}
 
Example 9
Project: TasksProject   File: StringUtils.java View source code Vote up 6 votes
public static final String Sha1(final String s) {
    try {
        MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();
        StringBuffer hexString = new StringBuffer();
        for (byte element : messageDigest) {
            String h = Integer.toHexString(0xFF & element);
            while (h.length() < 2) {
                h = "0" + h;
            }
            hexString.append(h);
        }
        return hexString.toString();
    }
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 10
Project: smack-xmpp   File: VCard.java View source code Vote up 6 votes
/**
 * Returns the SHA-1 Hash of the Avatar image.
 *
 * @return the SHA-1 Hash of the Avatar image.
 */
public String getAvatarHash() {
    byte[] bytes = getAvatar();
    if (bytes == null) {
        return null;
    }

    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("SHA-1");
    }
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }

    digest.update(bytes);
    return StringUtils.encodeHex(digest.digest());
}
 
Example 11
Project: Boxee-Thumb-Remote   File: BoxeeDiscovererThread.java View source code Vote up 6 votes
/**
 * Calculate the signature we need to send with the request. It is a string
 * containing the hex md5sum of the challenge and REMOTE_KEY.
 * 
 * @return signature string
 */
private String getSignature(String challenge) {
	MessageDigest digest;
	byte[] md5sum = null;
	try {
		digest = java.security.MessageDigest.getInstance("MD5");
		digest.update(challenge.getBytes());
		digest.update(REMOTE_KEY.getBytes());
		md5sum = digest.digest();
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}

	StringBuffer hexString = new StringBuffer();
	for (int k = 0; k < md5sum.length; ++k) {
		String s = Integer.toHexString((int) md5sum[k] & 0xFF);
		if (s.length() == 1)
			hexString.append('0');
		hexString.append(s);
	}
	return hexString.toString();
}
 
Example 12
Project: ABPlayer   File: StringHelper.java View source code Vote up 6 votes
public static String md5(String plaintext) {
	MessageDigest m;
	try {
		m = MessageDigest.getInstance("MD5");
		m.reset();
		m.update(("abitno&hellojane" + plaintext + " vplayer" + 7777777).getBytes());
		byte[] digest = m.digest();
		BigInteger bigInt = new BigInteger(1, digest);
		String hashtext = bigInt.toString(16);
		while (hashtext.length() < 32) {
			hashtext = "0" + hashtext;
		}
		return hashtext;
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 13
Project: vr-toolkit   File: MD5hash.java View source code Vote up 6 votes
public static String md5(String s) {
    try {
        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();
        
        StringBuffer hexString = new StringBuffer();
        for (int i=0; i<messageDigest.length; i++)
            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
        return hexString.toString();
        
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 14
Project: openmuc   File: Authentication.java View source code Vote up 6 votes
private String generateHash(String pwd) {
	StringBuilder hash = new StringBuilder();

	MessageDigest sha;
	try {
		sha = MessageDigest.getInstance("SHA-256");
		byte[] hashedBytes = sha.digest(pwd.getBytes());
		char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

		for (byte hashedByte : hashedBytes) {
			hash.append(digits[(hashedByte & 0xf0) >> 4]);
			hash.append(digits[(hashedByte & 0x0f)]);
		}

	} catch (NoSuchAlgorithmException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	return hash.toString();
}
 
Example 15
Project: CSipSimple-old   File: MD5.java View source code Vote up 6 votes
public static String MD5Hash(String s) {
       MessageDigest m = null;

       try {
               m = MessageDigest.getInstance("MD5");
       } catch (NoSuchAlgorithmException e) {
               e.printStackTrace();
               return "";
       }

       m.update(s.getBytes(),0,s.length());
       String hash = new BigInteger(1, m.digest()).toString(16);
       return hash;
}
 
Example 16
Project: mobile-mba-androidapp   File: Security.java View source code Vote up 6 votes
private static KeyPair generateRSAKeys() {
	KeyPair keypair = null;
	try {
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		keyGen.initialize(1024);
		keypair = keyGen.genKeyPair();
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
	return keypair;
}
 
Example 17
Project: blogracy   File: Hashes.java View source code Vote up 6 votes
public static String hash(String text) {
    String result = null;
    try {
           MessageDigest digester = MessageDigest.getInstance("SHA-1");
           byte[] digest = digester.digest(text.getBytes());
           result = base32.encodeAsString(digest);
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
	return result;
}
 
Example 18
Project: java-csp   File: DOMKeyValue.java View source code Vote up 6 votes
@Override
RSAPublicKey unmarshalKeyValue(Element kvtElem)
    throws MarshalException
{
    if (rsakf == null) {
        try {
            rsakf = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException
                ("unable to create RSA KeyFactory: " + e.getMessage());
        }
    }
    Element modulusElem = DOMUtils.getFirstChildElement(kvtElem);
    BigInteger modulus = decode(modulusElem);
    Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem);
    BigInteger exponent = decode(exponentElem);
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
    return (RSAPublicKey) generatePublicKey(rsakf, spec);
}
 
Example 19
Project: ics-openvpn   File: DigestUtils.java View source code Vote up 6 votes
/**
 * 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 RuntimeException
 *             when a [email protected] java.security.NoSuchAlgorithmException} is caught.
 */
static MessageDigest getDigest(String algorithm) {
    try {
        return MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 20
Project: CounterSign   File: RepositoryManagedSignatureProvider.java View source code Vote up 6 votes
@Override
public boolean validateSignature(byte[] sig, byte[] hash)
{
	String alg = config.getProperty(RepositoryManagedSignatureProviderFactory.SIGNATURE_ALGORITHM);
	String prov = config.getProperty(RepositoryManagedSignatureProviderFactory.JAVA_SIGNATURE_PROVIDER);
	
	boolean valid = false;
	
	try
	{
		Signature validate = Signature.getInstance(alg, prov);
		validate.initVerify(getPublicKey());
		validate.update(hash);
		valid = validate.verify(sig);
	}
	catch(NoSuchProviderException nspe)
	{
		throw new AlfrescoRuntimeException("Provider: " + prov + " was not found: " + nspe.getMessage());
	} 
	catch (NoSuchAlgorithmException nsae) 
	{
		throw new AlfrescoRuntimeException("Algorithm: " + alg + " is not available: " + nsae.getMessage());
	}
	catch(SignatureException se)
	{
		valid = false;
	}
	catch(InvalidKeyException ike)
	{
		valid = false;
	}
	
	return valid;
}
 
Example 21
Project: Magnolia   File: MD5CheckingFileExtractorOperation.java View source code Vote up 6 votes
protected MessageDigest getMessageDigest() {
    try {
        return MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Can't check files with md5: " + e.getMessage(), e);
    }
}
 
Example 22
Project: SharkFW   File: SharkCertificate.java View source code Vote up 6 votes
/***
 * Calculates the fingerprint of the certificate
 * @return SHA-256 fingerprint based of a string from the concatenated fields of the certificate
 * @throws SharkException
 */
@Override
public byte[] getFingerprint() throws SharkException {
    MessageDigest messageDigest;
    try {
        messageDigest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new SharkException(e.getMessage());
    }
    String concatenatedDataSet = this.subject.getName() + this.issuer.getName() + this.subjectPublicKey.toString() + this.validity.toString();
    return messageDigest.digest(concatenatedDataSet.getBytes());
}
 
Example 23
Project: sql-layer   File: MD5.java View source code Vote up 6 votes
@Override
protected void doEvaluate(TExecutionContext context, LazyList<? extends ValueSource> inputs, ValueTarget output)
{
    try
    {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte ret[] = md.digest(inputs.get(0).getBytes());
        
        output.putString(Strings.formatMD5(ret, true), null);
    }
    catch (NoSuchAlgorithmException ex)
    {
        throw new IllegalArgumentException(ex.getMessage());
    }
}
 
Example 24
Project: keycloak   File: HMACProvider.java View source code Vote up 6 votes
private static Mac getMAC(final Algorithm alg) {

        try {
            return Mac.getInstance(getJavaAlgorithm(alg));

        } catch (NoSuchAlgorithmException e) {

            throw new RuntimeException("Unsupported HMAC algorithm: " + e.getMessage(), e);
        }
    }
 
Example 25
Project: dk   File: Md5Utils.java View source code Vote up 6 votes
/**
 * MD5??????
 * 
 * @param str
 *            ???????
 * @return ???????
 */
public static String hash(String str) {
	String result = "";
	if (str == null) { // ????????????????
		return result;
	}
	try {
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] data = str.getBytes();
		int l = data.length;
		for (int i = 0; i < l; i++) {
			md.update(data[i]);
		}
		byte[] digest = md.digest();

		result = ByteUtils.byteArrayToHexString(digest);
	} catch (NoSuchAlgorithmException e) {
		throw new RuntimeException(e.getMessage(), e);
	}

	return result;
}
 
Example 26
Project: cloudbees-api-client   File: JarUtils.java View source code Vote up 6 votes
static MessageDigest getDigest(String algorithm) {
    try {
        return MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 27
Project: aws-sdk-android   File: S3CryptoModuleBase.java View source code Vote up 6 votes
protected final SecretKey generateCEK(
        final EncryptionMaterials kekMaterials,
        final Provider providerIn) {
    final String keygenAlgo =
            contentCryptoScheme.getKeyGeneratorAlgorithm();
    KeyGenerator generator;
    try {
        generator = providerIn == null ?
                KeyGenerator.getInstance(keygenAlgo) :
                KeyGenerator.getInstance(keygenAlgo, providerIn);
        generator.init(contentCryptoScheme.getKeyLengthInBits(),
                cryptoScheme.getSecureRandom());
        // set to true iff key encryption involves BC's public key
        boolean involvesBcPublicKey = false;
        KeyPair keyPair = kekMaterials.getKeyPair();
        if (keyPair != null) {
            String keyWrapAlgo = cryptoScheme
                    .getKeyWrapScheme()
                    .getKeyWrapAlgorithm(keyPair.getPublic());
            if (keyWrapAlgo == null) {
                Provider provider = generator.getProvider();
                String providerName = provider == null ?
                        null :
                        provider.getName();
                involvesBcPublicKey = CryptoRuntime.BOUNCY_CASTLE_PROVIDER
                        .equals(providerName);
            }
        }
        if (!involvesBcPublicKey) {
            return generator.generateKey();
        } else {
            for (int retry = 0; retry < 10; retry++) {
                // generate the random key until leading byte is nonzero
                // see https://github.com/aws/aws-sdk-android/issues/15
                SecretKey secretKey = generator.generateKey();
                if (secretKey.getEncoded()[0] != 0) {
                    return secretKey;
                }
            }
            // if using public BC key, this happens with p = 2^-80
            throw new AmazonClientException(
                    "Failed to generate secret key");
        }
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException(
                "Unable to generate envelope symmetric key:"
                        + e.getMessage(), e);
    }
}
 
Example 28
Project: InSide   File: CriptPassword.java View source code Vote up 6 votes
/**
 * Retona la password encriptada para ser guarda en la base de datos.
 * @param key
 * @return
 * @throws InSideException 
 * @throws NoSuchAlgorithmException
 */
public String getHashSH1(String key) throws InSideException  {
	MessageDigest md;
	String retorno = "";
	byte[] buffer = key.getBytes();
	try {
		md = MessageDigest.getInstance("SHA1");
		md.update(buffer);
		byte[] digest = md.digest();
		for (byte aux : digest) {
			int b = aux & 0xff;
			if (Integer.toHexString(b).length() == 1){
				retorno += "0";
			}
			retorno += Integer.toHexString(b);
		}
		return retorno;
	} catch (NoSuchAlgorithmException ex) {
		throw new InSideException("generalError", ex.getMessage(), ex);
	}
}
 
Example 29
Project: chbosync4android   File: RelaxedSSLTrustManager.java View source code Vote up 6 votes
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
		throws CertificateException {
	if (this.certKey == null) {
		// This is the Accept All certificates case.
		return;
	}

	// Otherwise, we have a certKey defined. We should now examine the one
	// we got from the server.
	// They match? All is good. They don't, throw an exception.
	String our_key = this.certKey.replaceAll("\\s+", "");
	try {
		// Assume self-signed root is okay?
		X509Certificate ss_cert = chain[0];
		String thumbprint = RelaxedSSLTrustManager.getThumbPrint(ss_cert);
		if (Log.isLoggable(Log.DEBUG)) {
			Log.debug(LOG_NAME, "Certificate Thumbprint: " + thumbprint);
		}
		if (our_key.equalsIgnoreCase(thumbprint)) {
			return;
		} else {
			throw new CertificateException("Certificate key [" + thumbprint + "] doesn't match expected value.");						
		}
	} catch (NoSuchAlgorithmException e) {
		throw new CertificateException("Unable to check self-signed cert, unknown algorithm. " + e.toString());
	}

}
 
Example 30
Project: dazzl   File: UUIDGenerator.java View source code Vote up 6 votes
public MessageDigest getHashAlgorithm()
{
    /*
     * Similar to the shared random number generator, it's not necessary to
     * synchronize initialization. However, use of the hash instance HAS to
     * be synchronized by the caller to prevent problems with multiple
     * threads updating digest etc.
     */
    if (mHasher == null)
    {
        try
        {
            mHasher = MessageDigest.getInstance("MD5");
        }
        catch (NoSuchAlgorithmException nex)
        {
            throw new Error(
                    "Couldn't instantiate an MD5 MessageDigest instance: "
                            + nex.toString());
        }
    }
    return mHasher;
}
 
Example 31
Project: transdroid   File: SelfSignedTrustManager.java View source code Vote up 6 votes
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	if (this.certKey == null) {
		throw new CertificateException("Requires a non-null certificate key in SHA-1 format to match.");
	}

	// Qe have a certKey defined. We should now examine the one we got from the server.
	// They match? All is good. They don't, throw an exception.
	String ourKey = this.certKey.replaceAll("[^a-fA-F0-9]+", "");
	try {
		// Assume self-signed root is okay?
		X509Certificate sslCert = chain[0];
		String thumbprint = SelfSignedTrustManager.getThumbPrint(sslCert);
		if (ourKey.equalsIgnoreCase(thumbprint)) {
			return;
		}

		CertificateException certificateException =
				new CertificateException("Certificate key [" + thumbprint + "] doesn't match expected value.");
		//Log.e(SelfSignedTrustManager.class.getSimpleName(), certificateException.toString());
		throw certificateException;

	} catch (NoSuchAlgorithmException e) {
		throw new CertificateException("Unable to check self-signed cert, unknown algorithm. " + e.toString());
	}

}
 
Example 32
Project: org.eclipse.ecr   File: Dialect.java View source code Vote up 6 votes
protected String makeName(String name, int maxNameSize) {
    if (name.length() > maxNameSize) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.toString(), e);
        }
        byte[] bytes = name.getBytes();
        digest.update(bytes, 0, bytes.length);
        name = name.substring(0, maxNameSize - 1 - 8);
        name += '_' + toHexString(digest.digest()).substring(0, 8);
    }
    name = storesUpperCaseIdentifiers() ? name.toUpperCase()
            : name.toLowerCase();
    name = name.replace(':', '_');
    return name;
}
 
Example 33
Project: Auie   File: UEString.java View source code Vote up 6 votes
/**
 * SHA256????(SHA256 Encryption)
 * @param str ????????(Require encrypted String)
 * @return String ???????(Encrypted String)
 */
public static String encryptSHA256(String str) {
	String ps = "";
	try {
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		md.update(str.getBytes());
		ps = transformHex(md.digest());
	} catch (NoSuchAlgorithmException e) {
		return e.toString();
	}
	return ps;
}
 
Example 34
Project: AcademicTorrents-Downloader   File: Storage.java View source code Vote up 6 votes
public void create () throws IOException
{
    // Calculate piece_hashes
    MessageDigest digest = null;
    try {
        digest = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException nsa) {
        throw new InternalError(nsa.toString());
    }

    byte[] piece_hashes = metainfo.getPieceHashes();

    byte[] piece = new byte[piece_size];
    for (int i = 0; i < pieces; i++) {
        int length = getUncheckedPiece(i, piece, 0);
        digest.update(piece, 0, length);
        byte[] hash = digest.digest();
        for (int j = 0; j < 20; j++) {
            piece_hashes[20 * i + j] = hash[j];
        }

        bitfield.set(i);

        if (listener != null) {
            listener.storageChecked(this, i, true);
        }
    }

    if (listener != null) {
        listener.storageAllChecked(this);
    }

    // Reannounce to force recalculating the info_hash.
    metainfo = metainfo.reannounce(metainfo.getAnnounce());
}
 
Example 35
Project: DrupalLoadTest   File: MD5.java View source code Vote up 6 votes
/**
    * Digest the input.
    *
    * @param input the data to be digested.
    * @return the md5-digested input
    */
   public static final byte[] digest(byte[] input)
   {
try 
{
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    return md5.digest(input);
}
catch (NoSuchAlgorithmException nsae)
{
    throw new Error(nsae.toString());
}
   }
 
Example 36
Project: hadoop   File: RegistrySecurity.java View source code Vote up 6 votes
/**
 * Generate a base-64 encoded digest of the idPasswordPair pair
 * @param idPasswordPair id:password
 * @return a string that can be used for authentication
 */
public String digest(String idPasswordPair) throws IOException {
  if (StringUtils.isEmpty(idPasswordPair) || !isValid(idPasswordPair)) {
    throw new IOException("Invalid id:password: " + idPasswordPair);
  }
  try {
    return DigestAuthenticationProvider.generateDigest(idPasswordPair);
  } catch (NoSuchAlgorithmException e) {
    // unlikely since it is standard to the JVM, but maybe JCE restrictions
    // could trigger it
    throw new IOException(e.toString(), e);
  }
}
 
Example 37
Project: bbb-java   File: FakeTrustManager.java View source code Vote up 6 votes
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        if( this.certKey == null ){
                // This is the Accept All certificates case.
                return;
        }

        // Otherwise, we have a certKey defined. We should now examine the one we got from the server.
        // They match? All is good. They don't, throw an exception.
        String our_key = this.certKey.replaceAll("\\s+", "");
        try {
        //Assume self-signed root is okay?
        X509Certificate ss_cert = chain[0];
                        String thumbprint = FakeTrustManager.getThumbPrint(ss_cert);
                        if( our_key.equalsIgnoreCase(thumbprint) ){
                                return;
                        }
                        else {
                                throw new CertificateException("Certificate key [" + thumbprint + "] doesn't match expected value.");
                        }
                } catch (NoSuchAlgorithmException e) {
                        throw new CertificateException("Unable to check self-signed cert, unknown algorithm. " + e.toString());
                }

}
 
Example 38
Project: protodroid   File: FakeTrustManager.java View source code Vote up 6 votes
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        if( this.certKey == null ){
                // This is the Accept All certificates case.
                return;
        }

        // Otherwise, we have a certKey defined. We should now examine the one we got from the server.
        // They match? All is good. They don't, throw an exception.
        String our_key = this.certKey.replaceAll("\\s+", "");
        try {
        //Assume self-signed root is okay?
        X509Certificate ss_cert = chain[0];
                        String thumbprint = FakeTrustManager.getThumbPrint(ss_cert);
                        //TLog.d(LOG_NAME, thumbprint);
                        if( our_key.equalsIgnoreCase(thumbprint) ){
                                return;
                        }
                        else {
                                throw new CertificateException("Certificate key [" + thumbprint + "] doesn't match expected value.");
                        }
                } catch (NoSuchAlgorithmException e) {
                        throw new CertificateException("Unable to check self-signed cert, unknown algorithm. " + e.toString());
                }

}
 
Example 39
Project: texai   File: Storage.java View source code Vote up 6 votes
/** Creates piece hashes for a new storage.
 *
 * @throws IOException when an input/output error occurs
 */
public void createPieceHashes() throws IOException {
  // Calculate piece_hashes
  MessageDigest digest = null;
  try {
    digest = MessageDigest.getInstance("SHA");
  } catch (NoSuchAlgorithmException nsa) {
    throw new InternalError(nsa.toString());    // NOPMD
  }

  final byte[] piece_hashes = metaInfo.getPieceHashes();

  final byte[] pieceBuffer = new byte[pieceSize];
  // i pieces
  for (int i = 0; i < nbrPieces; i++) {
    final int length = getUncheckedPiece(
            i, // the piece sequence number
            pieceBuffer, // the given buffer into which the piece is stored
            0); // the offest
    digest.update(
            pieceBuffer, // the array of bytes to hash
            0, // offset
            length); // length
    final byte[] piece_hash = digest.digest();
    // 20 bytes in a particular piece hash
    System.arraycopy(piece_hash, 0, piece_hashes, 20 * i, 20);

    bitField.set(i);
  }

  // Reannounce to force recalculating the info_hash.
  metaInfo = metaInfo.reannounce(metaInfo.getAnnounceURLString());
}
 
Example 40
Project: opennms_dashboard   File: User.java View source code Vote up 6 votes
/**
 * This method encrypts the password using MD5 hashing.
 *
 * @param aPassword
 *            the password to encrypt
 * @return the MD5 hash of the password, or null if the encryption fails
 * @throws java.lang.IllegalStateException if any.
 */
public static String encryptPassword(String aPassword) throws IllegalStateException {
    String encryptedPassword = null;

    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");

        // build the digest, get the bytes, convert to hexadecimal string
        // and return
        encryptedPassword = hexToString(digest.digest(aPassword.getBytes()));
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e.toString());
    }

    return encryptedPassword;
}
 
Example 41
Project: property-db   File: CertStore.java View source code Vote up 6 votes
private static CertStore handleException(NoSuchAlgorithmException e)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    Throwable cause = e.getCause();
    if (cause instanceof InvalidAlgorithmParameterException) {
        throw (InvalidAlgorithmParameterException)cause;
    }
    throw e;
}
 
Example 42
Project: JDK   File: CertStore.java View source code Vote up 6 votes
private static CertStore handleException(NoSuchAlgorithmException e)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    Throwable cause = e.getCause();
    if (cause instanceof InvalidAlgorithmParameterException) {
        throw (InvalidAlgorithmParameterException)cause;
    }
    throw e;
}
 
Example 43
Project: ikvm-openjdk   File: CertStore.java View source code Vote up 6 votes
private static CertStore handleException(NoSuchAlgorithmException e)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    Throwable cause = e.getCause();
    if (cause instanceof InvalidAlgorithmParameterException) {
        throw (InvalidAlgorithmParameterException)cause;
    }
    throw e;
}
 
Example 44
Project: ManagedRuntimeInitiative   File: CertStore.java View source code Vote up 6 votes
private static CertStore handleException(NoSuchAlgorithmException e)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    Throwable cause = e.getCause();
    if (cause instanceof InvalidAlgorithmParameterException) {
        throw (InvalidAlgorithmParameterException)cause;
    }
    throw e;
}
 
Example 45
Project: staash   File: TestChunking.java View source code Vote up 6 votes
public boolean compareMD5(byte[] written, byte[] read) {
	try {
		MessageDigest md = MessageDigest.getInstance(ENC1);
		byte[] wdigest = md.digest(written);
		byte[] rdigest = md.digest(read);
		return Arrays.equals(wdigest, rdigest);
	} catch (NoSuchAlgorithmException e) {
		// TODO Auto-generated catch block
		throw new RuntimeException(e.getCause());
	}
}
 
Example 46
Project: openjdk   File: CertStore.java View source code Vote up 6 votes
private static CertStore handleException(NoSuchAlgorithmException e)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    Throwable cause = e.getCause();
    if (cause instanceof InvalidAlgorithmParameterException) {
        throw (InvalidAlgorithmParameterException)cause;
    }
    throw e;
}
 
Example 47
Project: jstorm   File: AuthUtils.java View source code Vote up 6 votes
/**
 * Construct a JAAS configuration object per storm configuration file 
 * @param storm_conf Storm configuration 
 * @return JAAS configuration object
 */
public static Configuration GetConfiguration(Map storm_conf) {
    Configuration login_conf = null;

    //find login file configuration from Storm configuration  
    String loginConfigurationFile = (String)storm_conf.get("java.security.auth.login.config");
    if ((loginConfigurationFile != null) && (loginConfigurationFile.length()>0)) { 
        try {
            URI config_uri = new File(loginConfigurationFile).toURI();
            login_conf = Configuration.getInstance("JavaLoginConfig", new URIParameter(config_uri));
        } catch (NoSuchAlgorithmException ex1) {
            if (ex1.getCause() instanceof FileNotFoundException)
                throw new RuntimeException("configuration file "+loginConfigurationFile+" could not be found");
            else throw new RuntimeException(ex1);
        } catch (Exception ex2) {
            throw new RuntimeException(ex2);
        }
    }
    
    return login_conf;
}
 
Example 48
Project: openjdk8-jdk   File: CertStore.java View source code Vote up 6 votes
private static CertStore handleException(NoSuchAlgorithmException e)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    Throwable cause = e.getCause();
    if (cause instanceof InvalidAlgorithmParameterException) {
        throw (InvalidAlgorithmParameterException)cause;
    }
    throw e;
}
 
Example 49
Project: android_platform_libcore   File: CertStore.java View source code Vote up 6 votes
/**
 * Creates a new [email protected] CertStore} instance with the specified type and
 * initialized with the specified parameters.
 *
 * @param type
 *            the certificate store type.
 * @param params
 *            the certificate store parameters (may be [email protected] null}).
 * @return the new certificate store instance.
 * @throws NoSuchAlgorithmException
 *             if no provider can provide the specified certificate store
 *             type.
 * @throws InvalidAlgorithmParameterException
 *             if the specified parameters cannot be used to initialize this
 *             certificate store instance.
 * @throws NullPointerException if [email protected] type == null}
 */
public static CertStore getInstance(String type, CertStoreParameters params)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {
    if (type == null) {
        throw new NullPointerException("type == null");
    }
    try {
        Engine.SpiAndProvider sap = ENGINE.getInstance(type, params);
        return new CertStore((CertStoreSpi) sap.spi, sap.provider, type, params);
    } catch (NoSuchAlgorithmException e) {
        Throwable th = e.getCause();
        if (th == null) {
            throw e;
        } else {
            throw new InvalidAlgorithmParameterException(e.getMessage(), th);
        }
    }
}
 
Example 50
Project: classpath   File: SSLCipherSuite.java View source code Vote up 6 votes
public static final SSLCipherSuite getInstance (String name, Provider provider)
  throws NoSuchAlgorithmException
{
  SSLCipherSuite suite = null;
  try
    {
      suite = (SSLCipherSuite) Engine.getInstance (SERVICE, name, provider);
      suite.provider = provider;
    }
  catch (InvocationTargetException ite)
    {
      // XXX
      NoSuchAlgorithmException nsae = new NoSuchAlgorithmException (name);
      nsae.initCause (ite);
      throw nsae;
    }
  return suite;
}
 
Example 51
Project: JamVM-PH   File: SSLCipherSuite.java View source code Vote up 6 votes
public static final SSLCipherSuite getInstance (String name, Provider provider)
  throws NoSuchAlgorithmException
{
  SSLCipherSuite suite = null;
  try
    {
      suite = (SSLCipherSuite) Engine.getInstance (SERVICE, name, provider);
      suite.provider = provider;
    }
  catch (InvocationTargetException ite)
    {
      // XXX
      NoSuchAlgorithmException nsae = new NoSuchAlgorithmException (name);
      nsae.initCause (ite);
      throw nsae;
    }
  return suite;
}
 
Example 52
Project: android_platform_libcore   File: OpenSSLCipher.java View source code Vote up 6 votes
@Override
protected void engineSetMode(String modeStr) throws NoSuchAlgorithmException {
    final Mode mode;
    try {
        mode = Mode.valueOf(modeStr.toUpperCase(Locale.US));
    } catch (IllegalArgumentException e) {
        NoSuchAlgorithmException newE = new NoSuchAlgorithmException("No such mode: "
                + modeStr);
        newE.initCause(e);
        throw newE;
    }
    checkSupportedMode(mode);
    this.mode = mode;
}
 
Example 53
Project: android-libcore64   File: OpenSSLCipher.java View source code Vote up 6 votes
@Override
protected void engineSetMode(String modeStr) throws NoSuchAlgorithmException {
    final Mode mode;
    try {
        mode = Mode.valueOf(modeStr.toUpperCase(Locale.US));
    } catch (IllegalArgumentException e) {
        NoSuchAlgorithmException newE = new NoSuchAlgorithmException("No such mode: "
                + modeStr);
        newE.initCause(e);
        throw newE;
    }
    checkSupportedMode(mode);
    this.mode = mode;
}
 
Example 54
Project: ARTPart   File: OpenSSLCipher.java View source code Vote up 6 votes
@Override
protected void engineSetMode(String modeStr) throws NoSuchAlgorithmException {
    final Mode mode;
    try {
        mode = Mode.valueOf(modeStr.toUpperCase(Locale.US));
    } catch (IllegalArgumentException e) {
        NoSuchAlgorithmException newE = new NoSuchAlgorithmException("No such mode: "
                + modeStr);
        newE.initCause(e);
        throw newE;
    }
    checkSupportedMode(mode);
    this.mode = mode;
}
 
Example 55
Project: SecurePhoto   File: SPImage.java View source code Vote up 5 votes
public VerificationStatus checkIntegrity(SPValidator validator, byte[] inputHash) {
        byte[] calculatedHash = null;
        if (inputHash == null) {
            validator.log("No input hash");
            inputHash = new byte[0];
        }

        validator.log(String.format("Frame ID: %s", byteArrayToHex(header.uniqueFrameID)));


        try {
            MessageDigest messageDigest = MessageDigest.getInstance(SPImage.DIGEST_ALGORITHM);
            messageDigest.update(imageData);
            messageDigest.update(inputHash);
            calculatedHash = messageDigest.digest();


            if (verificationFactors != null) {
                validator.log("VerificationFactorData found");
                for (Class<Verifier> v : verificationFactors) {
                    VerificationFactorData factorData = verificationFactorData.get(v);

                    if (factorData != null) {
                        messageDigest.update(calculatedHash);
                        messageDigest.update(factorData.getHash());
                        calculatedHash = messageDigest.digest();
                    }
                }
            } else {
                validator.log("No VerificationFactorData present");
            }

            validator.log(String.format("Calculated hash: %s", byteArrayToHex(calculatedHash)));
//            validator.log("Signature TODO");

            FrameInfo info = validator.lookupFrame(header.uniqueFrameID);

            if (info != null) {
                byte[] submittedHash = DatatypeConverter.parseBase64Binary(info.imageHash);
                validator.log(String.format("Retrieving frame hash: %s", byteArrayToHex(submittedHash)));
                validator.log(String.format("Frame hash submitted: %s", new Date(info.issueDate * 1000).toString()));

                boolean validationOK = Arrays.equals(calculatedHash, submittedHash);

                if (validationOK) {
                    validator.log("Hash OK");
                    validator.log("Frame VERIFIED");

                    return VerificationStatus.OK;
                } else {
                    validator.log("Hash verification FAILED.");
                    return VerificationStatus.FAILED;
                }


            } else {
                validator.log("No frame record on server.");
            }

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return VerificationStatus.UNKNOWN;
    }
 
Example 56
Project: junrar-android   File: Engine.java View source code Vote up 5 votes
/**
 * Get the implementation for <i>algorithm</i> for service
 * <i>service</i> from <i>provider</i>, passing <i>initArgs</i> to the
 * SPI class's constructor (which cannot be null; pass a zero-length
 * array if the SPI takes no arguments). The service is e.g.
 * "Signature", and the algorithm "DSA".
 *
 * @param service   The service name.
 * @param algorithm The name of the algorithm to get.
 * @param provider  The provider to get the implementation from.
 * @param initArgs  The arguments to pass to the SPI class's
 *        constructor (cannot be null).
 * @return The engine class for the specified algorithm; the object
 *         returned is typically a subclass of the SPI class for that
 *         service, but callers should check that this is so.
 * @throws NoSuchAlgorithmException If the implementation cannot be
 *         found or cannot be instantiated.
 * @throws InvocationTargetException If the SPI class's constructor
 *         throws an exception.
 * @throws IllegalArgumentException If any of the four arguments are null.
 */
static Object getInstance(String service, String algorithm,
                          Provider provider, Object[] initArgs)
  throws InvocationTargetException, NoSuchAlgorithmException
{
  if (service == null || algorithm == null
      || provider == null || initArgs == null)
    throw new IllegalArgumentException();

  // If there is no property "service.algorithm"
  if (provider.getProperty(service + "." + algorithm) == null)
    {
      // Iterate through aliases, until we find the class name or resolve
      // too many aliases.
      String alias = null;
      int count = 0;
      while ((alias = provider.getProperty(
              ALG_ALIAS + service + "." + algorithm)) != null)
        {
          if (algorithm.equals(alias))  // Refers to itself!
            break;
          algorithm = alias;
          if (count++ > MAX_ALIASES)
            throw new NoSuchAlgorithmException("too many aliases");
        }
      if (provider.getProperty(service + "." + algorithm) == null)
        throw new NoSuchAlgorithmException(algorithm);
    }

  // Find and instantiate the implementation.
  Class clazz = null;
  ClassLoader loader = provider.getClass().getClassLoader();
  Constructor constructor = null;
  String error = algorithm;
  Throwable cause = null;

  try
    {
      if (loader != null)
        clazz = loader.loadClass(provider.getProperty(service+"."+algorithm));
      else
        clazz = Class.forName(provider.getProperty(service+"."+algorithm));
      constructor = getCompatibleConstructor(clazz, initArgs);
      return constructor.newInstance(initArgs);
    }
  catch (ClassNotFoundException cnfe)
    {
      cause = cnfe;
      error = "class not found: " + algorithm;
    }
  catch (IllegalAccessException iae)
    {
      cause = iae;
      error = "illegal access: " + iae.getMessage();
    }
  catch (InstantiationException ie)
    {
      cause = ie;
      error = "instantiation exception: " + ie.getMessage();
    }
  catch (ExceptionInInitializerError eiie)
    {
      cause = eiie;
      error = "exception in initializer: " + eiie.getMessage();
    }
  catch (SecurityException se)
    {
      cause = se;
      error = "security exception: " + se.getMessage();
    }
  catch (NoSuchMethodException nsme)
    {
      cause = nsme;
      error = "no appropriate constructor found";
    }

  NoSuchAlgorithmException nsae = new NoSuchAlgorithmException(error);
  if (cause != null)
    nsae.initCause (cause);
  throw nsae;
}