Java Code Examples for java.security.NoSuchAlgorithmException

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project 4308Cirrus, under directory /tendril-android-lib/src/main/java/edu/colorado/cs/cirrus/android/ssl/.

Source file: EasyX509TrustManager.java

  17 
vote

/** 
 * Constructor for EasyX509TrustManager.
 */
public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
  super();
  TrustManagerFactory factory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  factory.init(keystore);
  TrustManager[] trustmanagers=factory.getTrustManagers();
  if (trustmanagers.length == 0) {
    throw new NoSuchAlgorithmException("no trust manager found");
  }
  this.standardTrustManager=(X509TrustManager)trustmanagers[0];
}
 

Example 2

From project authme-2.0, under directory /src/uk/org/whoami/authme/security/.

Source file: PasswordSecurity.java

  16 
vote

public static String getHash(HashAlgorithm alg,String password) throws NoSuchAlgorithmException {
switch (alg) {
case MD5:
    return getMD5(password);
case SHA1:
  return getSHA1(password);
case SHA256:
String salt=createSalt(16);
return getSaltedHash(password,salt);
case WHIRLPOOL:
return getWhirlpool(password);
case XAUTH:
String xsalt=createSalt(12);
return getXAuth(password,xsalt);
default :
throw new NoSuchAlgorithmException("Unknown hash algorithm");
}
}
 

Example 3

From project AuthMe-Reloaded, under directory /src/main/java/uk/org/whoami/authme/security/.

Source file: PasswordSecurity.java

  16 
vote

public static String getHash(HashAlgorithm alg,String password) throws NoSuchAlgorithmException {
switch (alg) {
case MD5:
    return getMD5(password);
case SHA1:
  return getSHA1(password);
case SHA256:
String salt=createSalt(16);
return getSaltedHash(password,salt);
case MD5VB:
String salt2=createSalt(16);
return getSaltedMd5(password,salt2);
case WHIRLPOOL:
return getWhirlpool(password);
case XAUTH:
String xsalt=createSalt(12);
return getXAuth(password,xsalt);
case PHPBB:
return getPhpBB(password);
case PLAINTEXT:
return getPlainText(password);
default :
throw new NoSuchAlgorithmException("Unknown hash algorithm");
}
}
 

Example 4

From project AuthMe-Reloaded-Charge-fix, under directory /src/uk/org/whoami/authme/security/.

Source file: PasswordSecurity.java

  16 
vote

public static String getHash(HashAlgorithm alg,String password) throws NoSuchAlgorithmException {
switch (alg) {
case MD5:
    return getMD5(password);
case SHA1:
  return getSHA1(password);
case SHA256:
String salt=createSalt(16);
return getSaltedHash(password,salt);
case MD5VB:
String salt2=createSalt(16);
return getSaltedMd5(password,salt2);
case WHIRLPOOL:
return getWhirlpool(password);
case XAUTH:
String xsalt=createSalt(12);
return getXAuth(password,xsalt);
case PHPBB:
return getPhpBB(password);
case PLAINTEXT:
return getPlainText(password);
default :
throw new NoSuchAlgorithmException("Unknown hash algorithm");
}
}
 

Example 5

From project activemq-apollo, under directory /apollo-broker/src/main/scala/org/apache/activemq/apollo/broker/transport/.

Source file: TcpTransportFactory.java

  15 
vote

/** 
 * Allows subclasses of TcpTransportFactory to create custom instances of TcpTransport.
 */
protected TcpTransport createTransport(URI uri) throws NoSuchAlgorithmException, Exception {
  if (!uri.getScheme().equals("tcp")) {
    return null;
  }
  TcpTransport transport=new TcpTransport();
  return transport;
}
 

Example 6

From project adbcj, under directory /mysql/codec/src/main/java/org/adbcj/mysql/codec/.

Source file: MySqlClientEncoder.java

  15 
vote

public void encode(ClientRequest request,OutputStream out) throws IOException, NoSuchAlgorithmException {
  int length=request.getLength(charset);
  out.write(length & 0xFF);
  out.write(length >> 8 & 0xFF);
  out.write(length >> 16 & 0xFF);
  out.write(request.getPacketNumber());
  if (request instanceof CommandRequest) {
    encodeCommandRequest(out,(CommandRequest)request);
  }
 else   if (request instanceof LoginRequest) {
    encodeLoginRequest(out,(LoginRequest)request);
  }
 else {
    throw new IllegalStateException("Unable to encode message of type " + request.getClass().getName());
  }
}
 

Example 7

From project aether-core, under directory /aether-api/src/main/java/org/eclipse/aether/repository/.

Source file: AuthenticationDigest.java

  15 
vote

private static MessageDigest newDigest(){
  try {
    return MessageDigest.getInstance("SHA-1");
  }
 catch (  NoSuchAlgorithmException e) {
    try {
      return MessageDigest.getInstance("MD5");
    }
 catch (    NoSuchAlgorithmException ne) {
      throw new IllegalStateException(ne);
    }
  }
}
 

Example 8

From project agile, under directory /agile-api/src/main/java/org/headsupdev/agile/api/util/.

Source file: HashUtil.java

  15 
vote

public static String getMD5Hex(String in){
  MessageDigest messageDigest;
  try {
    messageDigest=java.security.MessageDigest.getInstance("MD5");
    messageDigest.update(in.getBytes(),0,in.length());
    return new BigInteger(1,messageDigest.digest()).toString(16);
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  return "";
}
 

Example 9

From project agit, under directory /agit/src/main/java/com/madgag/agit/util/.

Source file: DigestUtils.java

  15 
vote

static MessageDigest getDigest(String algorithm){
  try {
    return MessageDigest.getInstance(algorithm);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e.getMessage());
  }
}
 

Example 10

From project Airports, under directory /src/com/nadmm/airports/billing/.

Source file: Security.java

  15 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 11

From project ajah, under directory /ajah-crypto/src/main/java/com/ajah/crypto/.

Source file: Crypto.java

  15 
vote

/** 
 * Accepts a hexadecimal encoded version of the encrypted data and decrypts it.
 * @param encrypted hexadecimal encoded version of the encrypted data
 * @param keyString The key to use to decrypt the data.
 * @return Decrypted version.
 * @throws UnsupportedOperationException If there is a cryptographic error.
 */
public static String fromAES(final String encrypted,String keyString){
  final SecretKeySpec skeySpec=new SecretKeySpec(new BigInteger(keyString,16).toByteArray(),"AES");
  try {
    final Cipher cipher=Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE,skeySpec);
    return new String(cipher.doFinal(new BigInteger(encrypted,16).toByteArray()));
  }
 catch (  final InvalidKeyException e) {
    throw new UnsupportedOperationException(e);
  }
catch (  final IllegalBlockSizeException e) {
    throw new UnsupportedOperationException(e);
  }
catch (  final BadPaddingException e) {
    throw new UnsupportedOperationException(e);
  }
catch (  final NoSuchAlgorithmException e) {
    throw new UnsupportedOperationException(e);
  }
catch (  final NoSuchPaddingException e) {
    throw new UnsupportedOperationException(e);
  }
}
 

Example 12

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/webservice/.

Source file: HttpPostRequest.java

  15 
vote

private static String sha1(String raw) throws UnsupportedEncodingException, NoSuchAlgorithmException {
  byte[] bytes=raw.getBytes("UTF-8");
  MessageDigest md=MessageDigest.getInstance(MGF1ParameterSpec.SHA1.getDigestAlgorithm());
  md.update(bytes);
  byte[] digest=md.digest();
  return toHex(digest);
}
 

Example 13

From project alfredo, under directory /alfredo/src/main/java/com/cloudera/alfredo/util/.

Source file: Signer.java

  15 
vote

/** 
 * Returns then signature of a string.
 * @param str string to sign.
 * @return the signature for the string.
 */
protected String computeSignature(String str){
  try {
    MessageDigest md=MessageDigest.getInstance("SHA");
    md.update(str.getBytes());
    md.update(secret);
    byte[] digest=md.digest();
    Base64 base64=new Base64(0);
    return base64.encodeToString(digest);
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new RuntimeException("It should not happen, " + ex.getMessage(),ex);
  }
}
 

Example 14

From project AmDroid, under directory /AmenLib/src/main/java/com.jaeckel/amenoid/api/.

Source file: AmenHttpClient.java

  15 
vote

@Override protected ClientConnectionManager createClientConnectionManager(){
  SchemeRegistry registry=new SchemeRegistry();
  registry.register(new Scheme("http",80,PlainSocketFactory.getSocketFactory()));
  if (keyStoreStream != null) {
    registry.register(new Scheme("https",443,newSslSocketFactory()));
  }
 else {
    try {
      registry.register(new Scheme("https",443,new SSLSocketFactory(SSLContext.getInstance("Default"),new AllowAllHostnameVerifier())));
    }
 catch (    NoSuchAlgorithmException e) {
      e.printStackTrace();
      try {
        final SSLContext sslContext=SSLContext.getInstance("TLS");
        sslContext.init(null,null,null);
        registry.register(new Scheme("https",443,newSslSocketFactory()));
      }
 catch (      KeyManagementException e1) {
        throw new RuntimeException(e1);
      }
catch (      NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
      }
    }
  }
  ThreadSafeClientConnManager connMgr=new ThreadSafeClientConnManager(registry);
  connMgr.setDefaultMaxPerRoute(10);
  return connMgr;
}
 

Example 15

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/mysql/util/.

Source file: Security.java

  15 
vote

/** 
 * DOCUMENT ME!
 * @param salt DOCUMENT ME!
 * @param usingNewPasswords DOCUMENT ME!
 * @return DOCUMENT ME!
 * @throws NoSuchAlgorithmException if the message digest 'SHA-1' is not available.
 */
static byte[] getBinaryPassword(int[] salt,boolean usingNewPasswords) throws NoSuchAlgorithmException {
  int val=0;
  byte[] binaryPassword=new byte[SHA1_HASH_SIZE];
  if (usingNewPasswords) {
    int pos=0;
    for (int i=0; i < 4; i++) {
      val=salt[i];
      for (int t=3; t >= 0; t--) {
        binaryPassword[pos++]=(byte)(val & 255);
        val>>=8;
      }
    }
    return binaryPassword;
  }
  int offset=0;
  for (int i=0; i < 2; i++) {
    val=salt[i];
    for (int t=3; t >= 0; t--) {
      binaryPassword[t + offset]=(byte)(val % 256);
      val>>=8;
    }
    offset+=4;
  }
  MessageDigest md=MessageDigest.getInstance("SHA-1");
  md.update(binaryPassword,0,8);
  return md.digest();
}
 

Example 16

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/util/.

Source file: RandomGUID.java

  15 
vote

private void getRandomGUID(boolean secure){
  MessageDigest messageHash;
  StringBuilder sbValueBeforeHash=new StringBuilder();
  try {
    messageHash=MessageDigest.getInstance("SHA-1");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new ApplicationIllegalArgumentException(e);
  }
  long time=System.nanoTime();
  long rand=0;
  if (secure) {
    rand=MySecureRand.nextLong();
  }
 else {
    rand=MyRand.nextLong();
  }
  sbValueBeforeHash.append(SId);
  sbValueBeforeHash.append(":");
  sbValueBeforeHash.append(Long.toString(time));
  sbValueBeforeHash.append(":");
  sbValueBeforeHash.append(Long.toString(rand));
  valueBeforeHash=sbValueBeforeHash.toString();
  messageHash.update(valueBeforeHash.getBytes());
  byte[] array=messageHash.digest();
  StringBuffer sb=new StringBuffer();
  for (int j=0; j < array.length; ++j) {
    int b=array[j] & 0xFF;
    if (b < 0x10) {
      sb.append('0');
    }
    sb.append(Integer.toHexString(b));
  }
  valueAfterHash=sb.toString();
}
 

Example 17

From project android-bankdroid, under directory /src/com/liato/bankdroid/lockpattern/.

Source file: LockPatternUtils.java

  15 
vote

static byte[] patternToHash(List<LockPatternView.Cell> pattern){
  if (pattern == null) {
    return null;
  }
  final int patternSize=pattern.size();
  byte[] res=new byte[patternSize];
  for (int i=0; i < patternSize; i++) {
    LockPatternView.Cell cell=pattern.get(i);
    res[i]=(byte)(cell.getRow() * 3 + cell.getColumn());
  }
  try {
    MessageDigest md=MessageDigest.getInstance("SHA-1");
    byte[] hash=md.digest(res);
    return hash;
  }
 catch (  NoSuchAlgorithmException nsa) {
    return res;
  }
}
 

Example 18

From project android-client, under directory /xwiki-android-core/src/org/xwiki/android/security/.

Source file: Master.java

  15 
vote

public Master(){
  masterKey=getMasterKey();
  try {
    masterCipher=Cipher.getInstance("AES/ECB/PKCS7Padding");
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(TAG,"ENC algo missing: pwds will be saved in plaintext",e);
  }
catch (  NoSuchPaddingException e) {
    Log.e(TAG,"Padding scheme missing: pwds will be saved in plaintext",e);
  }
}
 

Example 19

From project android-client_1, under directory /src/com/googlecode/asmack/connection/impl/.

Source file: FeatureNegotiationEngine.java

  15 
vote

/** 
 * <p>Start TLS on the given connection.</p> <p><b>TODO:</b> This method uses a non-validating key manager.</p>
 * @throws NoSuchAlgorithmException If the requested encryption algorithmis not supported.
 * @throws KeyManagementException In case of a key managment error.
 * @throws IOException If the underlying stream dies.
 * @throws XmppTransportException In case of XML/XMPP related errors.
 */
protected void startTLS() throws NoSuchAlgorithmException, KeyManagementException, IOException, XmppTransportException {
  Log.d("BC/XMPP/Negotiation","StartTLS");
  xmppOutput.detach();
  xmppInput.detach();
  SSLContext context=SSLContext.getInstance("TLS");
  context.init(new KeyManager[]{},new javax.net.ssl.TrustManager[]{new UnTrustManager()},new java.security.SecureRandom());
  socket=context.getSocketFactory().createSocket(socket,socket.getInetAddress().getHostName(),socket.getPort(),true);
  socket.setKeepAlive(false);
  socket.setSoTimeout(0);
  inputStream=socket.getInputStream();
  outputStream=socket.getOutputStream();
  xmppOutput.attach(outputStream,true,false);
  xmppInput.attach(inputStream);
}
 

Example 20

From project android-donations-lib, under directory /org_donations/src/org/donations/google/.

Source file: Security.java

  15 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 21

From project Android-GifStitch, under directory /src/com/phunkosis/gifstitch/helpers/.

Source file: ShareHelper.java

  15 
vote

private static String generateSHA256(String offThis){
  String result="";
  try {
    MessageDigest md=MessageDigest.getInstance("SHA-256");
    md.update(offThis.getBytes());
    byte mdBytes[]=md.digest();
    result=bytesToHex(mdBytes);
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  return result;
}
 

Example 22

From project android-rackspacecloud, under directory /extensions/apachehc/src/main/java/org/jclouds/http/apachehc/config/.

Source file: ApacheHCHttpCommandExecutorServiceModule.java

  15 
vote

@Singleton @Provides ClientConnectionManager newClientConnectionManager(HttpParams params,X509HostnameVerifier verifier,Closer closer) throws NoSuchAlgorithmException, KeyManagementException {
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  Scheme http=new Scheme("http",PlainSocketFactory.getSocketFactory(),80);
  SSLContext context=SSLContext.getInstance("TLS");
  context.init(null,null,null);
  SSLSocketFactory sf=new SSLSocketFactory(context);
  sf.setHostnameVerifier(verifier);
  Scheme https=new Scheme("https",sf,443);
  SchemeRegistry sr=new SchemeRegistry();
  sr.register(http);
  sr.register(https);
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  final ClientConnectionManager cm=new ThreadSafeClientConnManager(params,schemeRegistry);
  closer.addToClose(new Closeable(){
    @Override public void close() throws IOException {
      cm.shutdown();
    }
  }
);
  return cm;
}
 

Example 23

From project android-sdk, under directory /src/main/java/com/mobeelizer/mobile/android/.

Source file: MobeelizerInternalDatabase.java

  15 
vote

private String getMd5(final String password){
  MessageDigest m;
  try {
    m=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException(e.getMessage(),e);
  }
  m.update(password.getBytes(),0,password.length());
  String hash=new BigInteger(1,m.digest()).toString(16);
  return hash;
}
 

Example 24

From project AndroidBillingLibrary, under directory /AndroidBillingLibrary/src/net/robotmedia/billing/security/.

Source file: DefaultSignatureValidator.java

  15 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
protected PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(BillingController.LOG_TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(BillingController.LOG_TAG,"Base64 decoding failed.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 25

From project androidpn, under directory /androidpn-server-bin-tomcat/src/org/androidpn/server/xmpp/ssl/.

Source file: SSLKeyManagerFactory.java

  15 
vote

public static KeyManager[] getKeyManagers(String storeType,String keystore,String keypass) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
  KeyManager[] keyManagers;
  if (keystore == null) {
    keyManagers=null;
  }
 else {
    if (keypass == null) {
      keypass="";
    }
    KeyStore keyStore=KeyStore.getInstance(storeType);
    keyStore.load(new FileInputStream(keystore),keypass.toCharArray());
    KeyManagerFactory keyFactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyFactory.init(keyStore,keypass.toCharArray());
    keyManagers=keyFactory.getKeyManagers();
  }
  return keyManagers;
}
 

Example 26

From project androidquery, under directory /src/com/androidquery/util/.

Source file: AQUtility.java

  15 
vote

private static byte[] getMD5(byte[] data){
  MessageDigest digest;
  try {
    digest=java.security.MessageDigest.getInstance("MD5");
    digest.update(data);
    byte[] hash=digest.digest();
    return hash;
  }
 catch (  NoSuchAlgorithmException e) {
    AQUtility.report(e);
  }
  return null;
}
 

Example 27

From project Android_1, under directory /encryption/src/com/novoda/.

Source file: Encrypt.java

  15 
vote

public String crypt(int mode,String encryption_subject) throws Base64DecoderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, UnsupportedEncodingException, IllegalBlockSizeException {
  final PBEParameterSpec ps=new javax.crypto.spec.PBEParameterSpec(SALT,20);
  final SecretKeyFactory kf=SecretKeyFactory.getInstance(ALGORITHM);
  final SecretKey k=kf.generateSecret(new javax.crypto.spec.PBEKeySpec(SECRET_KEY.toCharArray()));
  final Cipher crypter=Cipher.getInstance(CIPHER_TYPE);
  String result;
switch (mode) {
case Cipher.DECRYPT_MODE:
    crypter.init(Cipher.DECRYPT_MODE,k,ps);
  result=new String(crypter.doFinal(Base64.decode(encryption_subject)),CHARSET);
break;
case Cipher.ENCRYPT_MODE:
default :
crypter.init(Cipher.ENCRYPT_MODE,k,ps);
result=Base64.encode(crypter.doFinal(encryption_subject.getBytes(CHARSET)));
}
return result;
}
 

Example 28

From project android_5, under directory /src/aarddict/.

Source file: Volume.java

  15 
vote

public void verify(VerifyProgressListener listener) throws IOException, NoSuchAlgorithmException {
  FileInputStream fis=new FileInputStream(origFile);
  fis.skip(44);
  byte[] buff=new byte[1 << 16];
  MessageDigest m=MessageDigest.getInstance("SHA-1");
  int readCount;
  long totalReadCount=0;
  double totalBytes=origFile.length() - 44;
  boolean proceed=true;
  while ((readCount=fis.read(buff)) != -1) {
    m.update(buff,0,readCount);
    totalReadCount+=readCount;
    proceed=listener.updateProgress(this,totalReadCount / totalBytes);
  }
  fis.close();
  if (proceed) {
    BigInteger b=new BigInteger(1,m.digest());
    String calculated=b.toString(16);
    Log.d(TAG,"calculated: " + calculated + " actual: "+ sha1sum);
    listener.verified(this,calculated.equals(this.sha1sum));
  }
}
 

Example 29

From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/util/.

Source file: Util.java

  15 
vote

public static String getHash(String pin){
  MessageDigest digest;
  try {
    digest=MessageDigest.getInstance("SHA-1");
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e("Utils","NoSuchAlgorithm, storing in plain text...",e);
    return pin;
  }
  digest.reset();
  try {
    byte[] input=digest.digest(pin.getBytes("UTF-8"));
    String base64=Base64.encode(input);
    return base64;
  }
 catch (  UnsupportedEncodingException e) {
    Log.e("Utils","UnsupportedEncoding, storing in plain text...",e);
    return pin;
  }
}
 

Example 30

From project Android_Pusher, under directory /src/com/emorym/android_pusher/.

Source file: Pusher.java

  15 
vote

private String authenticate(String channelName){
  if (!isConnected()) {
    Log.e(LOG_TAG,"pusher not connected, can't create auth string");
    return null;
  }
  try {
    String stringToSign=mSocketId + ":" + channelName;
    SecretKey key=new SecretKeySpec(mPusherSecret.getBytes(),PUSHER_AUTH_ALGORITHM);
    Mac mac=Mac.getInstance(PUSHER_AUTH_ALGORITHM);
    mac.init(key);
    byte[] signature=mac.doFinal(stringToSign.getBytes());
    StringBuffer sb=new StringBuffer();
    for (int i=0; i < signature.length; ++i) {
      sb.append(Integer.toHexString((signature[i] >> 4) & 0xf));
      sb.append(Integer.toHexString(signature[i] & 0xf));
    }
    String authInfo=mPusherKey + ":" + sb.toString();
    Log.d(LOG_TAG,"Auth Info " + authInfo);
    return authInfo;
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
catch (  InvalidKeyException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 31

From project androvoip, under directory /src/com/mexuar/corraleta/protocol/.

Source file: ProtocolControlFrame.java

  15 
vote

/** 
 * Builds authentication IE. This method is called by sendAuthRep and sendRegReq.
 * @param iep The original IE
 * @param nip The new IE
 * @param pass The password
 * @see #sendAuthRep
 * @see #sendRegReq
 */
private void buildAuthInfoElements(InfoElement iep,InfoElement nip,String pass){
  nip.username=iep.username;
  nip.refresh=nip.refresh;
  if (_iep.authmethods != null) {
    int model=iep.authmethods.intValue();
    if ((model & 2) > 0) {
      try {
        final MessageDigest digest=MessageDigest.getInstance("MD5");
        digest.update(_iep.challenge.getBytes());
        digest.update(pass.getBytes());
        nip.md5Result=Binder.enHex(digest.digest(),null);
      }
 catch (      NoSuchAlgorithmException e) {
        android.util.Log.e("IAX2","MD5 not supported.");
        e.printStackTrace();
      }
    }
 else     if ((model & 1) > 0) {
      nip.md5Result=pass;
    }
  }
}
 

Example 32

From project ANNIS, under directory /annis-gui/src/main/java/annis/security/.

Source file: Crypto.java

  15 
vote

/** 
 * Hashes a string using SHA-256. 
 */
public static String calculateSHAHash(String s) throws NoSuchAlgorithmException, UnsupportedEncodingException {
  MessageDigest md=MessageDigest.getInstance("SHA-256");
  md.update(s.getBytes("UTF-8"));
  byte[] digest=md.digest();
  StringBuilder sbHashVal=new StringBuilder();
  for (  byte b : digest) {
    sbHashVal.append(String.format("%02x",b));
  }
  return sbHashVal.toString();
}
 

Example 33

From project annotare2, under directory /app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/utils/.

Source file: DigestUtil.java

  15 
vote

public static String md5Hex(String str){
  try {
    byte[] md5=MessageDigest.getInstance("MD5").digest(str.getBytes(Charsets.UTF_8));
    return toHexString(md5);
  }
 catch (  NoSuchAlgorithmException e) {
    throw logUnexpected("md5Hex error",e);
  }
}
 

Example 34

From project any23, under directory /core/src/main/java/org/apache/any23/util/.

Source file: MathUtils.java

  15 
vote

public static final String md5(String s){
  try {
    MessageDigest md5=MessageDigest.getInstance("MD5");
    md5.reset();
    md5.update(s.getBytes());
    byte[] digest=md5.digest();
    StringBuffer result=new StringBuffer();
    for (    byte b : digest) {
      result.append(Integer.toHexString(0xFF & b));
    }
    return result.toString();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException("Should never happen, MD5 is supported",e);
  }
}
 

Example 35

From project apps-for-android, under directory /Samples/Downloader/src/com/google/android/downloader/.

Source file: DownloaderActivity.java

  15 
vote

private MessageDigest createDigest() throws DownloaderException {
  MessageDigest digest;
  try {
    digest=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new DownloaderException("Couldn't create MD5 digest");
  }
  return digest;
}
 

Example 36

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/resource/arc/.

Source file: ARCResource.java

  15 
vote

public ARCResource(MetaData metaData,ResourceContainer container,ARCMetaData arcMetaData,InputStream raw){
  super(metaData.createChild(PAYLOAD_METADATA),container);
  envelope=metaData;
  this.arcMetaData=arcMetaData;
  this.raw=raw;
  metaData.putString(ENVELOPE_FORMAT,ENVELOPE_FORMAT_ARC);
  metaData.putLong(ARC_HEADER_LENGTH,arcMetaData.getHeaderLength());
  long leadingNL=arcMetaData.getLeadingNL();
  if (leadingNL > 0) {
    metaData.putLong(PAYLOAD_LEADING_SLOP_BYTES,leadingNL);
  }
  MetaData fields=metaData.createChild(ARC_HEADER_METADATA);
  fields.putString(URL_KEY,arcMetaData.getUrl());
  fields.putString(IP_KEY,arcMetaData.getIP());
  fields.putString(DATE_STRING_KEY,arcMetaData.getDateString());
  fields.putString(MIME_KEY,arcMetaData.getMime());
  fields.putLong(DECLARED_LENGTH_KEY,arcMetaData.getLength());
  countingIS=new CountingInputStream(new LimitInputStream(raw,arcMetaData.getLength()));
  try {
    digIS=new DigestInputStream(countingIS,MessageDigest.getInstance("sha1"));
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
}
 

Example 37

From project ardverk-commons, under directory /src/main/java/org/ardverk/security/.

Source file: MessageDigestUtils.java

  15 
vote

/** 
 * Creates and returns a  {@link MessageDigest} for the given algorithm.
 */
public static MessageDigest create(String algorithm){
  try {
    if (algorithm.equalsIgnoreCase(MessageDigestCRC32.NAME)) {
      return new MessageDigestCRC32();
    }
    return MessageDigest.getInstance(algorithm);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalArgumentException("algorithm=" + algorithm,e);
  }
}
 

Example 38

From project Arecibo, under directory /aggregator/src/main/java/com/ning/arecibo/aggregator/dictionary/.

Source file: EventDictionary.java

  15 
vote

private String getInputEventSignature(SortedMap<String,Class> typeMap){
  try {
    MessageDigest md5=MessageDigest.getInstance("MD5");
    for (    SortedMap.Entry<String,Class> entry : typeMap.entrySet()) {
      md5.update(entry.getKey().getBytes());
      md5.update(entry.getValue().getSimpleName().getBytes());
    }
    byte[] d=md5.digest();
    return UUIDUtil.md5ToString(d);
  }
 catch (  NoSuchAlgorithmException e) {
    return null;
  }
}
 

Example 39

From project arquillian-graphene, under directory /graphene-selenium/graphene-selenium-impl/src/main/java/org/jboss/arquillian/ajocado/utils/.

Source file: URLUtils.java

  15 
vote

/** 
 * Gets a MD5 digest of some resource obtains as input stream from connection to URL given by URL string.
 * @param url of the resource
 * @return MD5 message digest of resource
 * @throws IOException when connection to URL fails
 */
public static String resourceMd5Digest(String url) throws IOException {
  URLConnection connection=new URL(url).openConnection();
  InputStream in=connection.getInputStream();
  MessageDigest digest;
  try {
    digest=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new IllegalStateException("MD5 hashing is unsupported",ex);
  }
  byte[] buffer=new byte[MD5_BUFFER_SIZE];
  int read=0;
  while ((read=in.read(buffer)) > 0) {
    digest.update(buffer,0,read);
  }
  byte[] md5sum=digest.digest();
  BigInteger bigInt=new BigInteger(1,md5sum);
  return bigInt.toString(HEX_RADIX);
}
 

Example 40

From project artifactory-plugin, under directory /src/main/java/org/jfrog/hudson/generic/.

Source file: DependenciesDownloaderImpl.java

  15 
vote

public Map<String,String> invoke(File f,VirtualChannel channel) throws IOException {
  try {
    return FileChecksumCalculator.calculateChecksums(f,"md5","sha1");
  }
 catch (  NoSuchAlgorithmException e) {
    log.warn("Could not find checksum algorithm: " + e.getLocalizedMessage());
  }
  return null;
}
 

Example 41

From project AsmackService, under directory /src/com/googlecode/asmack/connection/impl/.

Source file: FeatureNegotiationEngine.java

  15 
vote

/** 
 * <p>Start TLS on the given connection.</p> <p><b>TODO:</b> This method uses a non-validating key manager.</p>
 * @throws NoSuchAlgorithmException If the requested encryption algorithmis not supported.
 * @throws KeyManagementException In case of a key managment error.
 * @throws IOException If the underlying stream dies.
 * @throws XmppTransportException In case of XML/XMPP related errors.
 */
protected void startTLS() throws NoSuchAlgorithmException, KeyManagementException, IOException, XmppTransportException {
  xmppOutput.detach();
  xmppInput.detach();
  SSLContext context=SSLContext.getInstance("TLS");
  context.init(new KeyManager[]{},new javax.net.ssl.TrustManager[]{new UnTrustManager()},new java.security.SecureRandom());
  socket=context.getSocketFactory().createSocket(socket,socket.getInetAddress().getHostName(),socket.getPort(),true);
  socket.setKeepAlive(false);
  socket.setSoTimeout(0);
  inputStream=socket.getInputStream();
  outputStream=socket.getOutputStream();
  xmppOutput.attach(outputStream,true,false);
  xmppInput.attach(inputStream);
}
 

Example 42

From project AuthDB, under directory /src/main/java/com/authdb/scripts/cms/.

Source file: DLE.java

  15 
vote

public static String hash(String password) throws SQLException {
  try {
    return passwordHash(password);
  }
 catch (  NoSuchAlgorithmException e) {
    Util.logging.StackTrace(e.getStackTrace(),Thread.currentThread().getStackTrace()[1].getMethodName(),Thread.currentThread().getStackTrace()[1].getLineNumber(),Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getFileName());
  }
catch (  UnsupportedEncodingException e) {
    Util.logging.StackTrace(e.getStackTrace(),Thread.currentThread().getStackTrace()[1].getMethodName(),Thread.currentThread().getStackTrace()[1].getLineNumber(),Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getFileName());
  }
  return "fail";
}
 

Example 43

From project avro, under directory /lang/java/avro/src/main/java/org/apache/avro/file/.

Source file: DataFileWriter.java

  15 
vote

private static byte[] generateSync(){
  try {
    MessageDigest digester=MessageDigest.getInstance("MD5");
    long time=System.currentTimeMillis();
    digester.update((UUID.randomUUID() + "@" + time).getBytes());
    return digester.digest();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 

Example 44

From project Axon-trader, under directory /users/src/main/java/org/axonframework/samples/trader/users/util/.

Source file: DigestUtils.java

  15 
vote

/** 
 * Calculate the SHA1 hash for a given string.
 * @param text the given text to hash to a SHA1
 * @return the SHA1 Hash
 */
public static String sha1(String text){
  Assert.notNull(text);
  try {
    MessageDigest md=MessageDigest.getInstance("SHA1");
    return hex(md.digest(text.getBytes("UTF-8")));
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new IllegalStateException("Unable to calculate hash. No SHA1 hasher available in this Java implementation",ex);
  }
catch (  UnsupportedEncodingException ex) {
    throw new IllegalStateException("Unable to calculate hash. UTF-8 encoding is not available in this Java implementation",ex);
  }
}
 

Example 45

From project azure-sdk-for-java-samples, under directory /WAAD.WebSSO.JAVA/java/code/libraries/waad-federation/src/main/java/com/microsoft/samples/federation/.

Source file: SamlTokenValidator.java

  15 
vote

private static boolean validateIssuerUsingCertificateThumbprint(SignableSAMLObject samlToken,String thumbprint) throws UnmarshallingException, ValidationException, CertificateException, NoSuchAlgorithmException {
  Signature signature=samlToken.getSignature();
  KeyInfo keyInfo=signature.getKeyInfo();
  X509Certificate pubKey=KeyInfoHelper.getCertificates(keyInfo).get(0);
  String thumbprintFromToken=SamlTokenValidator.getThumbPrintFromCert(pubKey);
  return thumbprintFromToken.equalsIgnoreCase(thumbprint);
}
 

Example 46

From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/.

Source file: Encryption.java

  15 
vote

public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
  MessageDigest md;
  md=MessageDigest.getInstance("SHA-1");
  byte[] sha1hash=new byte[40];
  md.update(text.getBytes("iso-8859-1"),0,text.length());
  sha1hash=md.digest();
  return util.convertToHex(sha1hash);
}
 

Example 47

From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.

Source file: MavenArtifact.java

  15 
vote

/** 
 * Computes the SHA1 signature of the file.
 */
public String getDigest() throws IOException {
  try {
    MessageDigest sig=MessageDigest.getInstance("SHA1");
    FileInputStream fin=new FileInputStream(resolve());
    byte[] buf=new byte[2048];
    int len;
    while ((len=fin.read(buf,0,buf.length)) >= 0)     sig.update(buf,0,len);
    return new String(Base64.encodeBase64(sig.digest()));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IOException(e);
  }
}
 

Example 48

From project BazaarUtils, under directory /src/com/android/vending/licensing/.

Source file: LicenseChecker.java

  15 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
private static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Could not decode from Base64.");
    throw new IllegalArgumentException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 49

From project bbb-java, under directory /src/main/java/org/transdroid/util/.

Source file: FakeTrustManager.java

  15 
vote

@Override public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
  if (this.certKey == null) {
    return;
  }
  String our_key=this.certKey.replaceAll("\\s+","");
  try {
    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 50

From project BeeQueue, under directory /src/org/beequeue/hash/.

Source file: MessageDigestUtils.java

  15 
vote

public static MessageDigest md(){
  try {
    return MessageDigest.getInstance("SHA1");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new BeeException(e);
  }
}
 

Example 51

From project BetterShop_1, under directory /src/me/jascotty2/lib/bukkit/.

Source file: FTP_PluginTracker.java

  15 
vote

public static String SUIDmd5Str(String txt) throws NoSuchAlgorithmException {
  if (txt == null) {
    txt="null";
  }
  byte hash[]=MessageDigest.getInstance("MD5").digest(txt.getBytes());
  String ret="";
  char chars[]={'q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m','~','1','2','3','4','5','6','7','8','9','0','-','+','Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M'};
  for (  byte b : hash) {
    ret+=chars[((int)b + 255) % chars.length];
  }
  return ret;
}
 

Example 52

From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/http/.

Source file: RequestHandler.java

  15 
vote

/** 
 * @author http://androidgenuine.com/?p=402
 */
public String hash(String str){
  try {
    MessageDigest digest=MessageDigest.getInstance("SHA-256");
    digest.update(str.getBytes());
    byte messageDigest[]=digest.digest();
    StringBuffer hexString=new StringBuffer();
    for (int i=0; i < messageDigest.length; i++) {
      String h=Integer.toHexString(0xFF & messageDigest[i]);
      while (h.length() < 2) {
        h="0" + h;
      }
      hexString.append(h);
    }
    return hexString.toString();
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  return "";
}
 

Example 53

From project bioclipse.speclipse, under directory /plugins/net.bioclipse.spectrum/src/spok/.

Source file: GenerateId.java

  15 
vote

/** 
 * Generates a unique identifier by generating a random number and getting its digest
 * @return the new SpectrumID
 */
public static String generateId(){
  try {
    SecureRandom prng=SecureRandom.getInstance("SHA1PRNG");
    String randomNum=new Integer(prng.nextInt()).toString();
    MessageDigest sha=MessageDigest.getInstance("SHA-1");
    byte[] result=sha.digest(randomNum.getBytes());
    spectrumID=hexEncode(result);
    spectrumID="sid_" + spectrumID;
  }
 catch (  NoSuchAlgorithmException ex) {
    System.err.println(ex);
  }
  return spectrumID;
}
 

Example 54

From project Bit4Tat, under directory /Bit4Tat/src/com/Bit4Tat/.

Source file: PaymentProcessorForMtGox.java

  15 
vote

HttpsURLConnection setupConnection(String urlString){
  SSLContext ctx=null;
  try {
    ctx=SSLContext.getInstance("TLS");
  }
 catch (  NoSuchAlgorithmException e1) {
    e1.printStackTrace();
  }
  try {
    ctx.init(new KeyManager[0],new TrustManager[]{new DefaultTrustManager()},new SecureRandom());
  }
 catch (  KeyManagementException e) {
    e.printStackTrace();
  }
  SSLContext.setDefault(ctx);
  URL url=null;
  try {
    url=new URL(urlString);
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
  }
  HttpsURLConnection conn=null;
  try {
    conn=(HttpsURLConnection)url.openConnection();
  }
 catch (  IOException e1) {
    e1.printStackTrace();
  }
  conn.setDoOutput(true);
  conn.setDoInput(true);
  conn.setHostnameVerifier(new HostnameVerifier(){
    @Override public boolean verify(    String arg0,    SSLSession arg1){
      return true;
    }
  }
);
  return conn;
}
 

Example 55

From project BombusLime, under directory /src/org/bombusim/lime/data/.

Source file: Vcard.java

  15 
vote

private void decodeAvatar(){
  int sz=Lime.getInstance().avatarSize;
  int szt=sz * 2;
  byte[] photobin=Base64.decode(base64Photo,Base64.DEFAULT);
  Bitmap avatarTmp=decodeBitmap(szt,photobin);
  int h=avatarTmp.getHeight();
  int w=avatarTmp.getWidth();
  if (h == 0 || w == 0) {
    photoHash=AVATAR_MISSING;
    return;
  }
  if (h > w) {
    w=(w * sz) / h;
    h=sz;
  }
 else {
    h=(h * sz) / w;
    w=sz;
  }
  Bitmap scaled=Bitmap.createScaledBitmap(avatarTmp,w,h,true);
  avatarTmp.recycle();
  if (h == w) {
    avatar=scaled;
  }
 else {
    avatar=Bitmap.createBitmap(sz,sz,Bitmap.Config.ARGB_8888);
    Canvas c=new Canvas(avatar);
    c.drawColor(Color.DKGRAY);
    c.drawBitmap(scaled,(sz - w) / 2,(sz - h) / 2,null);
  }
  try {
    MessageDigest sha1=MessageDigest.getInstance("SHA-1");
    photoHash=strconv.byteArrayToHexString(sha1.digest(photobin));
    LimeLog.d("Img SHA-1",jid,photoHash);
  }
 catch (  NoSuchAlgorithmException e) {
    photoHash=AVATAR_MISSING;
  }
}
 

Example 56

From project bookmarktodesktop-android-application, under directory /src/be/vbsteven/bmtodesk/.

Source file: MD5.java

  15 
vote

public static String md5(String s){
  String result="";
  try {
    MessageDigest digest=java.security.MessageDigest.getInstance("MD5");
    digest.update(s.getBytes());
    byte passDigest[]=digest.digest();
    StringBuffer hexPass=new StringBuffer();
    for (int i=0; i < passDigest.length; i++) {
      String h=Integer.toHexString(0xFF & passDigest[i]);
      while (h.length() < 2)       h="0" + h;
      hexPass.append(h);
    }
    result=hexPass.toString();
  }
 catch (  NoSuchAlgorithmException e) {
  }
  return result;
}
 

Example 57

From project brix-cms, under directory /brix-rmiserver/src/main/java/org/brixcms/rmiserver/.

Source file: PasswordEncoder.java

  15 
vote

/** 
 * Creates the hash of the password and concatenated salt
 * @param password password string
 * @param salt     salt string
 * @return SHA1 hash of concatenated password and salt
 */
private String hash(String password,String salt){
  String saltedPassword=salt + password;
  MessageDigest sha1;
  try {
    sha1=MessageDigest.getInstance("SHA1");
    sha1.update(saltedPassword.getBytes());
    byte[] saltedHash=sha1.digest();
    return bytesToHexString(saltedHash);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new NestableRuntimeException(e);
  }
}
 

Example 58

From project brut.apktool.smali, under directory /dexlib/src/main/java/org/jf/dexlib/.

Source file: DexFile.java

  15 
vote

/** 
 * Calculates the signature for the dex file in the given byte array, and then writes the signature to the appropriate location in the header containing in the array
 * @param bytes non-null; the bytes of the file
 */
public static void calcSignature(byte[] bytes){
  MessageDigest md;
  try {
    md=MessageDigest.getInstance("SHA-1");
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new RuntimeException(ex);
  }
  md.update(bytes,32,bytes.length - 32);
  try {
    int amt=md.digest(bytes,12,20);
    if (amt != 20) {
      throw new RuntimeException("unexpected digest write: " + amt + " bytes");
    }
  }
 catch (  DigestException ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 59

From project BSPAN---Bluetooth-Sensor-Processing-for-Android, under directory /AndroidSpineServer/src/com/t2/.

Source file: SharedPref.java

  15 
vote

private static String md5(String s){
  MessageDigest m=null;
  try {
    m=java.security.MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException e) {
  }
  if (m != null)   m.update(s.getBytes(),0,s.length());
  String hash=new BigInteger(1,m.digest()).toString();
  return hash;
}
 

Example 60

From project build-info, under directory /build-info-api/src/main/java/org/jfrog/build/api/util/.

Source file: FileChecksumCalculator.java

  15 
vote

/** 
 * Calculates the given file's checksums
 * @param fileToCalculate File to calculate
 * @param algorithms      Algorithms to use for calculation
 * @return Map with algorithm keys and checksum values
 * @throws NoSuchAlgorithmException Thrown if any of the given algorithms aren't supported
 * @throws IOException              Thrown if any error occurs while reading the file or calculating the checksums
 * @throws IllegalArgumentException TThrown if the given file to calc is null or non-existing or the algorithms varargs is null
 */
public static Map<String,String> calculateChecksums(File fileToCalculate,String... algorithms) throws NoSuchAlgorithmException, IOException {
  if ((fileToCalculate == null) || (!fileToCalculate.isFile())) {
    throw new IllegalArgumentException("Cannot read checksums of null or non-existent file.");
  }
  if (algorithms == null) {
    throw new IllegalArgumentException("Checksum algorithms cannot be null.");
  }
  if (algorithms.length == 0) {
    return Maps.newHashMap();
  }
  return calculate(fileToCalculate,algorithms);
}
 

Example 61

From project candlepin, under directory /src/main/java/org/candlepin/model/.

Source file: KeyPairCurator.java

  15 
vote

/** 
 * Lookup the keypair for this consumer. If none exists, a pair will be generated. Returns the java.security.KeyPair, not our internal KeyPair.
 * @return server-wide keypair.
 */
public java.security.KeyPair getConsumerKeyPair(Consumer c){
  KeyPair cpKeyPair=c.getKeyPair();
  if (cpKeyPair == null) {
    try {
      java.security.KeyPair newPair=pki.generateNewKeyPair();
      cpKeyPair=new KeyPair(newPair.getPrivate(),newPair.getPublic());
      create(cpKeyPair);
      c.setKeyPair(cpKeyPair);
    }
 catch (    NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }
  }
  java.security.KeyPair returnMe=new java.security.KeyPair(cpKeyPair.getPublicKey(),cpKeyPair.getPrivateKey());
  return returnMe;
}
 

Example 62

From project capedwarf-blue, under directory /appidentity/src/main/java/org/jboss/capedwarf/appidentity/.

Source file: CertificateGenerator.java

  15 
vote

public KeyPair generateKeyPair(){
  try {
    KeyPairGenerator generator=KeyPairGenerator.getInstance("RSA","BC");
    generator.initialize(KEY_SIZE,new SecureRandom());
    return generator.generateKeyPair();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException("Cannot generate RSA key pair",e);
  }
catch (  NoSuchProviderException e) {
    throw new RuntimeException("Cannot generate RSA key pair",e);
  }
}
 

Example 63

From project capedwarf-green, under directory /server-api/src/main/java/org/jboss/capedwarf/server/api/security/impl/.

Source file: BasicSecurityProvider.java

  15 
vote

public String hash(String... strings){
  if (strings == null || strings.length == 0)   throw new IllegalArgumentException("Null or empty strings: " + Arrays.toString(strings));
  try {
    MessageDigest m=MessageDigest.getInstance("MD5");
    StringBuilder builder=new StringBuilder();
    for (    String s : strings)     builder.append(s);
    builder.append(SALT);
    byte[] bytes=builder.toString().getBytes();
    m.update(bytes,0,bytes.length);
    BigInteger i=new BigInteger(1,m.digest());
    return String.format("%1$032X",i);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalArgumentException(e);
  }
}
 

Example 64

From project Carolina-Digital-Repository, under directory /admin/src/main/java/edu/unc/lib/dl/util/.

Source file: Checksum.java

  15 
vote

/** 
 * Constructor for Checksum class
 */
public Checksum(){
  try {
    initializeMessageDigest();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException("The default algorithm should be available.");
  }
}
 

Example 65

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/authentication/handler/.

Source file: DefaultPasswordEncoder.java

  15 
vote

public String encode(final String password){
  if (password == null) {
    return null;
  }
  try {
    MessageDigest messageDigest=MessageDigest.getInstance(this.encodingAlgorithm);
    if (StringUtils.hasText(this.characterEncoding)) {
      messageDigest.update(password.getBytes(this.characterEncoding));
    }
 else {
      messageDigest.update(password.getBytes());
    }
    final byte[] digest=messageDigest.digest();
    return getFormattedText(digest);
  }
 catch (  final NoSuchAlgorithmException e) {
    throw new SecurityException(e);
  }
catch (  final UnsupportedEncodingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 66

From project cascading, under directory /src/core/cascading/util/.

Source file: Util.java

  15 
vote

public static String createID(byte[] bytes){
  try {
    return getHex(MessageDigest.getInstance("MD5").digest(bytes));
  }
 catch (  NoSuchAlgorithmException exception) {
    throw new RuntimeException("unable to digest string");
  }
}
 

Example 67

From project caseconductor-platform, under directory /utest-common/src/main/java/com/utest/util/.

Source file: EncodeUtil.java

  15 
vote

public static String encode(final String plaintext){
  try {
    final byte[] plain=plaintext.getBytes();
    byte[] hashed;
    final MessageDigest sha=MessageDigest.getInstance(ALGORITHM);
    sha.update(plain);
    hashed=sha.digest();
    final StringBuffer sb=new StringBuffer();
    final int length=hashed.length;
    for (int i=0; i < (length) && i < hashed.length; i++) {
      sb.append(Character.forDigit((hashed[i] >>> 4) & 0xf,16));
      sb.append(Character.forDigit(hashed[i] & 0xf,16));
    }
    return sb.toString();
  }
 catch (  final NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}