Java Code Examples for java.security.InvalidKeyException

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 tinfoil-sms, under directory /branches/crypto-dev/strippedcastle/src/org/spongycastle/jcajce/provider/asymmetric/ec/.

Source file: ECUtil.java

  22 
vote

public static AsymmetricKeyParameter generatePrivateKeyParameter(PrivateKey key) throws InvalidKeyException {
  if (key instanceof ECPrivateKey) {
    ECPrivateKey k=(ECPrivateKey)key;
    ECParameterSpec s=k.getParameters();
    if (s == null) {
      s=BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();
    }
    return new ECPrivateKeyParameters(k.getD(),new ECDomainParameters(s.getCurve(),s.getG(),s.getN(),s.getH(),s.getSeed()));
  }
  throw new InvalidKeyException("can't identify EC private key.");
}
 

Example 2

From project DTE, under directory /src/cl/nic/dte/extension/.

Source file: DTEDefTypeExtensionHandler.java

  21 
vote

public static void timbrar(DTEDefType dte,CAFType caf,PrivateKey pKey) throws TimbreException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
  PublicKey pubKey=null;
  try {
    pubKey=caf.getPublicKey();
  }
 catch (  InvalidKeySpecException e1) {
    throw new InvalidKeyException(Utilities.exceptions.getString("TIMBRE_ERROR_BAD_KEY") + ": " + e1.getMessage());
  }
  if (dte.isSetDocumento())   timbrar(dte.getDocumento(),caf.getCAFforDocument(),pubKey,pKey);
 else   if (dte.isSetLiquidacion())   timbrar(dte.getLiquidacion(),caf.getCAFforLiquidacion(),pubKey,pKey);
 else   if (dte.isSetExportaciones())   timbrar(dte.getExportaciones(),caf.getCAFforExportacion(),pubKey,pKey);
}
 

Example 3

From project keepassdroid, under directory /src/org/bouncycastle/jce/provider/.

Source file: JCEBlockCipher.java

  21 
vote

protected void engineInit(int opmode,Key key,SecureRandom random) throws InvalidKeyException {
  try {
    engineInit(opmode,key,(AlgorithmParameterSpec)null,random);
  }
 catch (  InvalidAlgorithmParameterException e) {
    throw new InvalidKeyException(e.getMessage());
  }
}
 

Example 4

From project connectbot, under directory /src/sk/vx/connectbot/util/.

Source file: PubkeyUtils.java

  20 
vote

public static String convertToOpenSSHFormat(PublicKey pk,String origNickname) throws IOException, InvalidKeyException {
  String nickname=origNickname;
  if (nickname == null)   nickname="[email protected]";
  if (pk instanceof RSAPublicKey) {
    String data="ssh-rsa ";
    data+=String.valueOf(Base64.encode(RSASHA1Verify.encodeSSHRSAPublicKey((com.trilead.ssh2.signature.RSAPublicKey)convertToTrilead(pk))));
    return data + " " + nickname;
  }
 else   if (pk instanceof DSAPublicKey) {
    String data="ssh-dss ";
    data+=String.valueOf(Base64.encode(DSASHA1Verify.encodeSSHDSAPublicKey((com.trilead.ssh2.signature.DSAPublicKey)convertToTrilead(pk))));
    return data + " " + nickname;
  }
  throw new InvalidKeyException("Unknown key type");
}
 

Example 5

From project dnieprov, under directory /src/org/dnieprov/jce/provider/.

Source file: DnieSignature.java

  20 
vote

@Override protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
  if (!(privateKey instanceof DniePrivateKey)) {
    throw new InvalidKeyException("Key not found in driver");
  }
  DniePrivateKey tmpDnieKey=(DniePrivateKey)privateKey;
  Enumeration<DnieCard> cards=driver.getCards();
  boolean found=false;
  while (cards.hasMoreElements()) {
    DnieCard card=cards.nextElement();
    if (tmpDnieKey.inCard(card)) {
      found=true;
      this.dnieKey=tmpDnieKey;
    }
  }
  if (!found) {
    throw new InvalidKeyException("Key not found in driver");
  }
}
 

Example 6

From project eucalyptus, under directory /clc/modules/crypto/src/javax/crypto/.

Source file: SealedObject.java

  20 
vote

/** 
 * Retrieves the original (encapsulated) object. <p>This method creates a cipher for the algorithm that had been used in the sealing operation. If the default provider package provides an implementation of that algorithm, an instance of Cipher containing that implementation is used. If the algorithm is not available in the default package, other packages are searched. The Cipher object is initialized for decryption, using the given <code>key</code> and the parameters (if any) that had been used in the sealing operation. <p>The encapsulated object is unsealed and de-serialized, before it is returned.
 * @param key the key used to unseal the object.
 * @return the original object.
 * @exception IOException if an error occurs during de-serialiazation.
 * @exception ClassNotFoundException if an error occurs duringde-serialiazation.
 * @exception NoSuchAlgorithmException if the algorithm to unseal theobject is not available.
 * @exception InvalidKeyException if the given key cannot be used to unsealthe object (e.g., it has the wrong algorithm).
 * @exception NullPointerException if <code>key</code> is null.
 */
public final Object getObject(Key key) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException {
  if (key == null) {
    throw new NullPointerException("key is null");
  }
  try {
    return unseal(key,null);
  }
 catch (  NoSuchProviderException nspe) {
    throw new NoSuchAlgorithmException("algorithm not found");
  }
catch (  IllegalBlockSizeException ibse) {
    throw new InvalidKeyException(ibse.getMessage());
  }
catch (  BadPaddingException bpe) {
    throw new InvalidKeyException(bpe.getMessage());
  }
}
 

Example 7

From project JGlobus, under directory /ssl-proxies/src/main/java/org/globus/gsi/.

Source file: OpenSSLKey.java

  20 
vote

private void parseKeyAlgorithm(BufferedReader in) throws IOException, InvalidKeyException {
  String next=in.readLine();
  while (next != null) {
    if (next.indexOf("PRIVATE KEY") != -1) {
      keyAlg=getKeyAlgorithm(next);
      break;
    }
    next=in.readLine();
  }
  if (next == null) {
    throw new InvalidKeyException("noPrivateKey");
  }
  if (keyAlg == null) {
    throw new InvalidKeyException("algNotSup");
  }
}
 

Example 8

From project miso-lims, under directory /integration-tools/src/main/java/uk/ac/bbsrc/tgac/miso/integration/util/.

Source file: SignatureHelper.java

  20 
vote

public static boolean validateSignature(String url,String signatureString,String apiKey) throws InvalidKeyException, Exception {
  if (url == null || signatureString == null || apiKey == null) {
    throw new InvalidKeyException("Cannot verify signature when url, signature or api key are null!");
  }
  log.debug("VALIDATING: " + url + " :: "+ signatureString+ " :: "+ apiKey);
  String publicKey=SignatureHelper.getPublicKey(apiKey);
  if (publicKey == null)   return false;
  Signature signature=Signature.getInstance(ALGORITHM);
  signature.initVerify(decodePublicKey(publicKey));
  signature.update(url.getBytes());
  try {
    return signature.verify(Base64.decodeBase64(signatureString));
  }
 catch (  SignatureException e) {
    log.info("FAILED TO VERIFY SIGNATURE: " + signature.toString());
    return false;
  }
}
 

Example 9

From project Sage-Mobile-Calc, under directory /src/org/connectbot/util/.

Source file: PubkeyUtils.java

  20 
vote

public static String convertToOpenSSHFormat(PublicKey pk,String origNickname) throws IOException, InvalidKeyException {
  String nickname=origNickname;
  if (nickname == null)   nickname="[email protected]";
  if (pk instanceof RSAPublicKey) {
    String data="ssh-rsa ";
    data+=String.valueOf(Base64.encode(RSASHA1Verify.encodeSSHRSAPublicKey((com.trilead.ssh2.signature.RSAPublicKey)convertToTrilead(pk))));
    return data + " " + nickname;
  }
 else   if (pk instanceof DSAPublicKey) {
    String data="ssh-dss ";
    data+=String.valueOf(Base64.encode(DSASHA1Verify.encodeSSHDSAPublicKey((com.trilead.ssh2.signature.DSAPublicKey)convertToTrilead(pk))));
    return data + " " + nickname;
  }
  throw new InvalidKeyException("Unknown key type");
}
 

Example 10

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

Source file: Security.java

  19 
vote

/** 
 * Verifies that the signature from the server matches the computed signature on the data.  Returns true if the data is correctly signed.
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey,String signedData,String signature){
  if (Consts.DEBUG) {
    Log.i(TAG,"signature: " + signature);
  }
  Signature sig;
  try {
    sig=Signature.getInstance(SIGNATURE_ALGORITHM);
    sig.initVerify(publicKey);
    sig.update(signedData.getBytes());
    if (!sig.verify(Base64.decode(signature))) {
      Log.e(TAG,"Signature verification failed.");
      return false;
    }
    return true;
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(TAG,"NoSuchAlgorithmException.");
  }
catch (  InvalidKeyException e) {
    Log.e(TAG,"Invalid key specification.");
  }
catch (  SignatureException e) {
    Log.e(TAG,"Signature exception.");
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
  }
  return false;
}
 

Example 11

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

Source file: Crypto.java

  19 
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 android-client, under directory /xwiki-android-core/src/org/xwiki/android/security/.

Source file: Master.java

  19 
vote

/** 
 * Encrypt a secret string.
 * @param plainTextPwd
 * @return BASE64 encoded password cypher text string.
 */
public String encryptPassword(String plainTextPwd){
  if (masterCipher == null)   return plainTextPwd;
  byte[] input=null;
  try {
    input=plainTextPwd.getBytes("UTF8");
    masterCipher.init(Cipher.ENCRYPT_MODE,masterKey);
    byte[] output=new byte[masterCipher.getOutputSize(input.length)];
    int outputLen=masterCipher.update(input,0,input.length,output,0);
    masterCipher.doFinal(output,outputLen);
    String out=Base64.encodeToString(output,true);
    return out;
  }
 catch (  InvalidKeyException e) {
    Log.e(TAG,"invalid key. In Master");
  }
catch (  ShortBufferException e) {
    e.printStackTrace();
  }
catch (  IllegalBlockSizeException e) {
    Log.d(TAG,"",e);
  }
catch (  BadPaddingException e) {
    e.printStackTrace();
  }
catch (  UnsupportedEncodingException e) {
    Log.e(TAG,"UTF8 not supported ?");
  }
  return plainTextPwd;
}
 

Example 13

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

Source file: Security.java

  19 
vote

/** 
 * Verifies that the signature from the server matches the computed signature on the data. Returns true if the data is correctly signed.
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey,String signedData,String signature){
  if (Consts.DEBUG) {
    Log.i(TAG,"signature: " + signature);
  }
  Signature sig;
  try {
    sig=Signature.getInstance(SIGNATURE_ALGORITHM);
    sig.initVerify(publicKey);
    sig.update(signedData.getBytes());
    if (!sig.verify(Base64.decode(signature))) {
      Log.e(TAG,"Signature verification failed.");
      return false;
    }
    return true;
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(TAG,"NoSuchAlgorithmException.");
  }
catch (  InvalidKeyException e) {
    Log.e(TAG,"Invalid key specification.");
  }
catch (  SignatureException e) {
    Log.e(TAG,"Signature exception.");
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
  }
  return false;
}
 

Example 14

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

Source file: DefaultSignatureValidator.java

  19 
vote

protected boolean validate(PublicKey publicKey,String signedData,String signature){
  Signature sig;
  try {
    sig=Signature.getInstance(SIGNATURE_ALGORITHM);
    sig.initVerify(publicKey);
    sig.update(signedData.getBytes());
    if (!sig.verify(Base64.decode(signature))) {
      Log.e(BillingController.LOG_TAG,"Signature verification failed.");
      return false;
    }
    return true;
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(BillingController.LOG_TAG,"NoSuchAlgorithmException");
  }
catch (  InvalidKeyException e) {
    Log.e(BillingController.LOG_TAG,"Invalid key specification");
  }
catch (  SignatureException e) {
    Log.e(BillingController.LOG_TAG,"Signature exception");
  }
catch (  Base64DecoderException e) {
    Log.e(BillingController.LOG_TAG,"Base64 decoding failed");
  }
  return false;
}
 

Example 15

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

Source file: Encrypt.java

  19 
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 16

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

Source file: Pusher.java

  19 
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 17

From project azure4j-blog-samples, under directory /Log4J/CustomLog4JAppender/src/com/persistent/azure/logger/.

Source file: AzureTableStorageAppender.java

  19 
vote

/** 
 * The method adds the log message to the Windows Azure Table storage depending upon the layout.
 * @param event 
 */
@Override protected synchronized void append(LoggingEvent event){
  String messageLevel=event.getLevel().toString();
  if (this.layout == null) {
    errorHandler.error("layout not specified",null,ErrorCode.MISSING_LAYOUT);
    return;
  }
  String message=this.layout.format(event);
  try {
    CloudTableClient cloudTableClient=TableClient.getTableClient(storageEndpoint,accountName,accountKey,tableName);
    makeEntryIntoAzureTableStorage(cloudTableClient,messageLevel,message);
  }
 catch (  InvalidKeyException e) {
    e.printStackTrace();
  }
catch (  StorageException e) {
    e.printStackTrace();
  }
catch (  URISyntaxException e) {
    e.printStackTrace();
  }
}
 

Example 18

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

Source file: JBossAppIdentityService.java

  19 
vote

private byte[] sign(byte[] bytes,PrivateKey privateKey){
  try {
    Signature dsa=Signature.getInstance("SHA256WithRSA","BC");
    dsa.initSign(privateKey);
    dsa.update(bytes);
    return dsa.sign();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new AppIdentityServiceFailureException("Cannot sign: " + e);
  }
catch (  NoSuchProviderException e) {
    throw new AppIdentityServiceFailureException("Cannot sign: " + e);
  }
catch (  InvalidKeyException e) {
    throw new AppIdentityServiceFailureException("Cannot sign: " + e);
  }
catch (  SignatureException e) {
    throw new AppIdentityServiceFailureException("Cannot sign: " + e);
  }
}
 

Example 19

From project clutter, under directory /src/clutter/hypertoolkit/security/.

Source file: CipherText.java

  19 
vote

public ClearText decrypt(SecretKey secretKey) throws MessageIntegrityException {
  try {
    Cipher cipher=Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE,secretKey);
    return new ClearText(cipher.doFinal(bytes));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  NoSuchPaddingException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeyException e) {
    throw new RuntimeException(e);
  }
catch (  IllegalBlockSizeException e) {
    throw new MessageIntegrityException();
  }
catch (  BadPaddingException e) {
    throw new MessageIntegrityException();
  }
}
 

Example 20

From project cogroo4, under directory /lang/pt_br/cogroo-addon/src/org/cogroo/addon/community/.

Source file: CommunityLogic.java

  19 
vote

public static String[] getCategoriesForUser(String userName,String token,XPropertySet authProgressBar) throws CogrooException {
  String[] categories=null;
  try {
    RestUtil rest=new RestUtil();
    Map<String,String> data=new HashMap<String,String>();
    SecurityUtil security=new SecurityUtil();
    KeyPair kp=security.genKeyPair();
    byte[] key=kp.getPublic().getEncoded();
    data.put("user",userName);
    data.put("pubKey",security.encodeURLSafe(key));
    authProgressBar.setPropertyValue("ProgressValue",70);
    Map<String,String> respData=rest.post(ROOT,"saveClientSecurityKey",data);
    String encodedEncryptedBKey=respData.get("encryptedSecretKey");
    byte[] encryptedBKey=security.decodeURLSafe(encodedEncryptedBKey);
    data.clear();
    data.put("username",userName);
    data.put("token",security.encodeURLSafe(security.encrypt(kp.getPrivate(),encryptedBKey,token)));
    authProgressBar.setPropertyValue("ProgressValue",80);
    respData=rest.post(ROOT,"getErrorCategoriesForUser",data);
    String cat=respData.get("categories");
    categories=cat.split("\\|");
  }
 catch (  InvalidKeyException ex) {
    LOG.log(Level.SEVERE,"InvalidKeyException should not happen.",ex);
    throw new CogrooException(CogrooExceptionMessages.INTERNAL_ERROR,new String[]{ex.getLocalizedMessage()},ex);
  }
catch (  com.sun.star.uno.Exception ex) {
    LOG.log(Level.SEVERE,"UNO Exception should not happen.",ex);
    throw new CogrooException(CogrooExceptionMessages.INTERNAL_ERROR,new String[]{ex.getLocalizedMessage()},ex);
  }
  return categories;
}
 

Example 21

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.

Source file: IdentityApplic.java

  19 
vote

public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
  prop=new Properties();
  prop.load(new FileInputStream("ferryinpres.properties"));
  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  Socket sock=new Socket(prop.getProperty("IDENTITY_SERVER"),Integer.parseInt(prop.getProperty("IDENTITY_PORT")));
  ObjectOutputStream out=new ObjectOutputStream(sock.getOutputStream());
  ObjectInputStream in=new ObjectInputStream(sock.getInputStream());
  SecretKey sessionKey=keyExchange(in,out);
  Cipher cryptor=Cipher.getInstance("DES/ECB/PKCS5Padding");
  cryptor.init(Cipher.ENCRYPT_MODE,sessionKey);
  Cipher decryptor=Cipher.getInstance("DES/ECB/PKCS5Padding");
  decryptor.init(Cipher.DECRYPT_MODE,sessionKey);
  login(in,out,cryptor,decryptor);
}
 

Example 22

From project cp-common-utils, under directory /src/com/clarkparsia/common/io/.

Source file: EncryptedFile.java

  19 
vote

/** 
 * Initialize the ciphers based on the given secret key
 * @param theKey the key to use to create the ciphers
 */
private void initCiphers(SecretKey theKey){
  AlgorithmParameterSpec aSpec=new IvParameterSpec(IV);
  try {
    mEncryptCipher=Cipher.getInstance("DES/CBC/PKCS5Padding");
    mEncryptCipher.init(Cipher.ENCRYPT_MODE,theKey,aSpec);
    mDecryptCipher=createDecryptCipher(theKey);
  }
 catch (  java.security.InvalidAlgorithmParameterException e) {
    throw new IllegalStateException(e);
  }
catch (  javax.crypto.NoSuchPaddingException e) {
    throw new IllegalStateException(e);
  }
catch (  java.security.NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
  }
catch (  java.security.InvalidKeyException e) {
    throw new IllegalStateException(e);
  }
}
 

Example 23

From project crest, under directory /core/src/main/java/org/codegist/crest/security/oauth/v1/.

Source file: OAuthsV1.java

  19 
vote

static List<EncodedPair> oauth(VariantProvider variant,OAuthToken consumerOAuthToken,OAuthToken accessOAuthToken,MethodType methodType,String url,EncodedPair[] parameters,EncodedPair... extrasOAuthParams) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
  List<EncodedPair> oauthParams=oauthParamsFor(variant,consumerOAuthToken,accessOAuthToken,extrasOAuthParams);
  List<EncodedPair> toSign=new ArrayList<EncodedPair>(oauthParams);
  toSign.addAll(asList(parameters));
  String signature=sign(consumerOAuthToken,accessOAuthToken,methodType,url,toSign);
  oauthParams.add(pair("oauth_signature",signature));
  return oauthParams;
}
 

Example 24

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/util/.

Source file: Util.java

  19 
vote

public static byte[] decryptAES(byte[] cipherText,byte[] key){
  try {
    SecretKeySpec skeySpec=new SecretKeySpec(key,"AES");
    Cipher aesCipher=Cipher.getInstance("AES");
    aesCipher.init(Cipher.DECRYPT_MODE,skeySpec);
    ByteArrayOutputStream cipherOut=new ByteArrayOutputStream();
    CipherOutputStream aesOut=new CipherOutputStream(cipherOut,aesCipher);
    aesOut.write(cipherText);
    aesOut.close();
    return cipherOut.toByteArray();
  }
 catch (  InvalidKeyException e) {
    throw new RuntimeException(e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  NoSuchPaddingException e) {
    throw new RuntimeException(e);
  }
catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 25

From project encfs-java, under directory /src/main/java/org/mrpdaemon/sec/encfs/.

Source file: EncFSCrypto.java

  19 
vote

/** 
 * Create a new Mac object for the given key.
 * @param key Key to create a new Mac for.
 * @return New Mac object.
 * @throws InvalidKeyException Passed key is not valid
 * @throws EncFSUnsupportedException HMAC SHA-1 not supported by this runtime
 */
public static Mac newMac(Key key) throws InvalidKeyException, EncFSUnsupportedException {
  Mac hmac;
  try {
    hmac=Mac.getInstance("HmacSHA1");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new EncFSUnsupportedException(e);
  }
  SecretKeySpec hmacKey=new SecretKeySpec(key.getEncoded(),"HmacSHA1");
  hmac.init(hmacKey);
  return hmac;
}
 

Example 26

From project figgo, under directory /src/main/java/br/octahedron/figgo/modules/admin/util/.

Source file: Route53Util.java

  19 
vote

public static void createDomain(String domain,String accessId,String accessKey,String hostedZoneId) throws Route53Exception {
  try {
    HTTPRequest request=new HTTPRequest(new URL(ROUTE53_SERVER + VERSION_SPEC + HOSTED_ZONE_COMMAND+ hostedZoneId+ RRSET),HTTPMethod.POST);
    String requestBody=generateRequestBody(domain);
    logger.fine(requestBody);
    request.setPayload(requestBody.getBytes());
    signRequest(request,accessId,accessKey);
    HTTPResponse response=urlFetchService.fetch(request);
    if (response.getResponseCode() != 200) {
      logger.fine("Unable to create domain: " + domain);
      String out=new String(response.getContent());
      if (out.contains(EXISTS_DOMAIN_MESSAGE)) {
        throw new DomainAlreadyExistsException(domain);
      }
 else {
        throw new Route53Exception(out);
      }
    }
  }
 catch (  MalformedURLException e) {
    logger.log(Level.WARNING,"Unexpected error: " + e.getMessage(),e);
  }
catch (  InvalidKeyException e) {
    logger.log(Level.WARNING,"Unexpected error: " + e.getMessage(),e);
  }
catch (  InvalidKeySpecException e) {
    logger.log(Level.WARNING,"Unexpected error: " + e.getMessage(),e);
  }
catch (  NoSuchAlgorithmException e) {
    logger.log(Level.WARNING,"Unexpected error: " + e.getMessage(),e);
  }
catch (  IOException e) {
    logger.log(Level.WARNING,"Unexpected error: " + e.getMessage(),e);
  }
}
 

Example 27

From project FlipDroid, under directory /lib/weibo4j/src/weibo4j/http/.

Source file: OAuth.java

  19 
vote

/** 
 * Computes RFC 2104-compliant HMAC signature.
 * @param data the data to be signed
 * @return signature
 * @see <a href="http://oauth.net/core/1.0/#rfc.section.9.2.1">OAuth Core - 9.2.1.  Generating Signature</a>
 */
String generateSignature(String data,OAuthToken token){
  byte[] byteHMAC=null;
  try {
    Mac mac=Mac.getInstance(HMAC_SHA1);
    SecretKeySpec spec;
    if (null == token) {
      String oauthSignature=encode(consumerSecret) + "&";
      spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
    }
 else {
      if (null == token.getSecretKeySpec()) {
        String oauthSignature=encode(consumerSecret) + "&" + encode(token.getTokenSecret());
        spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
        token.setSecretKeySpec(spec);
      }
      spec=token.getSecretKeySpec();
    }
    mac.init(spec);
    byteHMAC=mac.doFinal(data.getBytes());
  }
 catch (  InvalidKeyException e) {
    e.printStackTrace();
  }
catch (  NoSuchAlgorithmException ignore) {
  }
  return new BASE64Encoder().encode(byteHMAC);
}
 

Example 28

From project flume, under directory /flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/encryption/.

Source file: AESCTRNoPaddingProvider.java

  19 
vote

private static Cipher getCipher(Key key,int mode,byte[] parameters){
  try {
    Cipher cipher=Cipher.getInstance(TYPE);
    cipher.init(mode,key,new IvParameterSpec(parameters));
    return cipher;
  }
 catch (  Exception e) {
    String msg="Unable to load key using transformation: " + TYPE;
    if (e instanceof InvalidKeyException) {
      try {
        int maxAllowedLen=Cipher.getMaxAllowedKeyLength(TYPE);
        if (maxAllowedLen < 256) {
          msg+="; Warning: Maximum allowed key length = " + maxAllowedLen + " with the available JCE security policy files. Have you"+ " installed the JCE unlimited strength jurisdiction policy"+ " files?";
        }
      }
 catch (      NoSuchAlgorithmException ex) {
        msg+="; Unable to find specified algorithm?";
      }
    }
    LOG.error(msg,e);
    throw Throwables.propagate(e);
  }
}
 

Example 29

From project Gaggle, under directory /src/com/geeksville/billing/.

Source file: Security.java

  19 
vote

/** 
 * Verifies that the signature from the server matches the computed signature on the data. Returns true if the data is correctly signed.
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey,String signedData,String signature){
  if (Consts.DEBUG) {
    Log.i(TAG,"signature: " + signature);
  }
  Signature sig;
  try {
    sig=Signature.getInstance(SIGNATURE_ALGORITHM);
    sig.initVerify(publicKey);
    sig.update(signedData.getBytes());
    if (!sig.verify(Base64.decode(signature))) {
      Log.e(TAG,"Signature verification failed.");
      return false;
    }
    return true;
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(TAG,"NoSuchAlgorithmException.");
  }
catch (  InvalidKeyException e) {
    Log.e(TAG,"Invalid key specification.");
  }
catch (  SignatureException e) {
    Log.e(TAG,"Signature exception.");
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
  }
  return false;
}
 

Example 30

From project Game_3, under directory /payments/server/src/playn/payments/server/.

Source file: JWTEncodedServiceImp.java

  19 
vote

private JsonToken createToken(String iat,String exp,PurchaseRequest purchaseRequest) throws InvalidKeyException, NullPurchaseMetaDataException {
  Calendar cal=Calendar.getInstance();
  HmacSHA256Signer signer=new HmacSHA256Signer(iss,null,secret.getBytes());
  JsonToken token=new JsonToken(signer);
  token.setAudience(aud);
  token.setParam("typ",typ);
  if (iat == null) {
    token.setIssuedAt(new Instant(cal.getTimeInMillis()));
  }
 else {
    token.setIssuedAt(new Instant(Long.parseLong(iat)));
  }
  if (exp == null) {
    token.setExpiration(new Instant(cal.getTimeInMillis() + timespan));
  }
 else {
    token.setExpiration(new Instant(Long.parseLong(exp)));
  }
  JsonObject request=new JsonObject();
  request.addProperty("name",purchaseRequest.name());
  request.addProperty("description",purchaseRequest.description());
  request.addProperty("price",purchaseRequest.price());
  request.addProperty("currencyCode",purchaseRequest.currencyCode());
  request.addProperty("sellerData",purchaseRequest.sellerData());
  JsonObject payload=token.getPayloadAsJsonObject();
  payload.add("request",request);
  return token;
}
 

Example 31

From project GeoBI, under directory /print/src/main/java/org/mapfish/print/map/readers/google/.

Source file: GoogleConfig.java

  19 
vote

URI signURI(URI uri) throws UnsupportedEncodingException, URISyntaxException {
  try {
    String[] path=uri.toString().substring(uri.toString().indexOf(uri.getPath())).split("#",2);
    String signedURI=uri.toString() + "&signature=" + signer.signature(path[0]);
    if (path.length > 1) {
      signedURI+=path[1];
    }
    return new URI(signedURI);
  }
 catch (  InvalidKeyException e) {
    throw new RuntimeException(e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 

Example 32

From project Gibberbot, under directory /src/net/java/otr4j/crypto/.

Source file: OtrCryptoEngineImpl.java

  19 
vote

public byte[] sha256Hmac(byte[] b,byte[] key,int length) throws OtrCryptoException {
  SecretKeySpec keyspec=new SecretKeySpec(key,"HmacSHA256");
  javax.crypto.Mac mac;
  try {
    mac=javax.crypto.Mac.getInstance("HmacSHA256");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new OtrCryptoException(e);
  }
  try {
    mac.init(keyspec);
  }
 catch (  InvalidKeyException e) {
    throw new OtrCryptoException(e);
  }
  byte[] macBytes=mac.doFinal(b);
  if (length > 0) {
    byte[] bytes=new byte[length];
    ByteBuffer buff=ByteBuffer.wrap(macBytes);
    buff.get(bytes);
    return bytes;
  }
 else {
    return macBytes;
  }
}
 

Example 33

From project Gmote, under directory /gmoteserver/src/org/gmote/server/.

Source file: StringEncrypter.java

  19 
vote

public static synchronized String readPasswordFromFile(){
  ObjectInputStream is;
  try {
    is=new ObjectInputStream(new FileInputStream(SystemPaths.PASSWORD.getFullPath()));
    ByteContainer cipherText;
    cipherText=(ByteContainer)is.readObject();
    is.close();
    StringEncrypter se=new StringEncrypter();
    return se.decrypt(cipherText.getCipherText());
  }
 catch (  FileNotFoundException e) {
    LOGGER.log(Level.SEVERE,e.getMessage(),e);
  }
catch (  IOException e) {
    LOGGER.log(Level.SEVERE,e.getMessage(),e);
  }
catch (  InvalidKeyException e) {
    LOGGER.log(Level.SEVERE,e.getMessage(),e);
  }
catch (  NoSuchAlgorithmException e) {
    LOGGER.log(Level.SEVERE,e.getMessage(),e);
  }
catch (  NoSuchPaddingException e) {
    LOGGER.log(Level.SEVERE,e.getMessage(),e);
  }
catch (  InvalidKeySpecException e) {
    LOGGER.log(Level.SEVERE,e.getMessage(),e);
  }
catch (  IllegalBlockSizeException e) {
    LOGGER.log(Level.SEVERE,e.getMessage(),e);
  }
catch (  BadPaddingException e) {
    LOGGER.log(Level.SEVERE,e.getMessage(),e);
  }
catch (  ClassNotFoundException e) {
    LOGGER.log(Level.SEVERE,e.getMessage(),e);
  }
  return "";
}
 

Example 34

From project GradeCalculator-Android, under directory /GradeCalculator/src/com/jetheis/android/grades/billing/.

Source file: Security.java

  19 
vote

public static boolean isCorrectSignature(String signedData,String signature){
  PublicKey publicKey;
  try {
    byte[] decodedKey=Base64.decode(PUBLIC_KEY_64,0);
    KeyFactory keyFactory=KeyFactory.getInstance("RSA");
    publicKey=keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(Constants.TAG,"NoSuchAlgoritmException: " + e.getLocalizedMessage());
    return false;
  }
catch (  InvalidKeySpecException e) {
    Log.e(Constants.TAG,"InvalidKeySpecException: " + e.getLocalizedMessage());
    return false;
  }
  Signature sig;
  try {
    sig=Signature.getInstance("SHA1withRSA");
    sig.initVerify(publicKey);
    sig.update(signedData.getBytes());
    if (!sig.verify(Base64.decode(signature,0))) {
      Log.e(Constants.TAG,"Bad Google Play signature! Possible security breach!");
      return false;
    }
    return true;
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(Constants.TAG,"NoSuchAlgorithmException: " + e.getLocalizedMessage());
    return false;
  }
catch (  InvalidKeyException e) {
    Log.e(Constants.TAG,"InvalidKeyException: " + e.getLocalizedMessage());
    return false;
  }
catch (  SignatureException e) {
    Log.e(Constants.TAG,"SignatureException: " + e.getLocalizedMessage());
    return false;
  }
}
 

Example 35

From project greenhouse, under directory /src/main/java/com/springsource/greenhouse/database/upgrade/v3/.

Source file: CipherUtils.java

  19 
vote

public static void initCipher(Cipher cipher,int mode,SecretKey secretKey,byte[] salt,int iterationCount){
  try {
    cipher.init(mode,secretKey,new PBEParameterSpec(salt,iterationCount));
  }
 catch (  InvalidKeyException e) {
    throw new IllegalArgumentException("Unable to initialize due to invalid secret key",e);
  }
catch (  InvalidAlgorithmParameterException e) {
    throw new IllegalStateException("Unable to initialize due to invalid decryption parameter spec",e);
  }
}
 

Example 36

From project http-testing-harness, under directory /server-provider/src/main/java/org/sonatype/tests/http/server/jetty/behaviour/.

Source file: NTLMAuth.java

  19 
vote

private Cipher getCipher(byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
  final Cipher ecipher=Cipher.getInstance("DES/ECB/NoPadding");
  key=setupKey(key);
  ecipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(key,"DES"));
  return ecipher;
}
 

Example 37

From project ISAcreator, under directory /src/main/java/org/isatools/isacreator/common/.

Source file: EncryptedObject.java

  19 
vote

/** 
 * Generates a key given a passphrase using the PBEWithMD5AndDES algorithm
 * @param passphrase - The passphrase to generate the key with
 * @throws NoSuchAlgorithmException 
 * @throws NoSuchPaddingException   
 * @throws InvalidKeyException      
 * @throws InvalidKeySpecException  
 * @throws InvalidAlgorithmParameterException *
 */
public void generateKey(String passphrase) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, InvalidAlgorithmParameterException {
  KeySpec keySpec=new PBEKeySpec(passphrase.toCharArray(),salt,iterationCount);
  SecretKey secretKey=SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
  encryptCipher=Cipher.getInstance(secretKey.getAlgorithm());
  decryptCipher=Cipher.getInstance(secretKey.getAlgorithm());
  AlgorithmParameterSpec paramSpec=new PBEParameterSpec(salt,iterationCount);
  encryptCipher.init(Cipher.ENCRYPT_MODE,secretKey,paramSpec);
  decryptCipher.init(Cipher.DECRYPT_MODE,secretKey,paramSpec);
}
 

Example 38

From project JavaStory, under directory /Core/src/main/java/javastory/client/.

Source file: LoginCrypto.java

  19 
vote

public static String decryptRSA(final String EncryptedPassword){
  try {
    final Cipher cipher=Cipher.getInstance("RSA/NONE/OAEPPadding","BC");
    final BigInteger modulus=new BigInteger("107657795738756861764863218740655861479186575385923787150128619142132921674398952720882614694082036467689482295621654506166910217557126105160228025353603544726428541751588805629215516978192030682053419499436785335057001573080195806844351954026120773768050428451512387703488216884037312069441551935633523181351");
    final BigInteger privateExponent=new BigInteger("5550691850424331841608142211646492148529402295329912519344562675759756203942720314385192411176941288498447604817211202470939921344057999440566557786743767752684118754789131428284047255370747277972770485804010629706937510833543525825792410474569027516467052693380162536113699974433283374142492196735301185337");
    final RSAPrivateKeySpec privKey1=new RSAPrivateKeySpec(modulus,privateExponent);
    final PrivateKey privKey=RSAKeyFactory.generatePrivate(privKey1);
    final byte[] bytes=Hex.decode(EncryptedPassword);
    cipher.init(Cipher.DECRYPT_MODE,privKey);
    return new String(cipher.doFinal(bytes));
  }
 catch (  final InvalidKeyException ike) {
    System.err.println("[LoginCrypto] Error initalizing the encryption cipher.  Make sure you're using the Unlimited Strength cryptography jar files.");
  }
catch (  final NoSuchProviderException nspe) {
    System.err.println("[LoginCrypto] Security provider not found");
  }
catch (  final Exception e) {
    System.err.println("[LoginCrypto] Error occured with RSA password decryption.");
  }
  return "";
}
 

Example 39

From project java_binding_v1, under directory /src/com/tripit/auth/.

Source file: OAuthCredential.java

  19 
vote

public boolean validateSignature(URI requestUri) throws URISyntaxException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
  List<NameValuePair> argList=URLEncodedUtils.parse(requestUri,"UTF-8");
  SortedMap<String,String> args=new TreeMap<String,String>();
  for (  NameValuePair arg : argList) {
    args.put(arg.getName(),arg.getValue());
  }
  String signature=args.remove("oauth_signature");
  String baseUrl=new URI(requestUri.getScheme(),requestUri.getUserInfo(),requestUri.getAuthority(),requestUri.getPort(),requestUri.getPath(),null,requestUri.getFragment()).toString();
  return (signature != null && signature.equals(generateSignature(baseUrl,args)));
}
 

Example 40

From project jboss-sasl, under directory /src/main/java/org/jboss/sasl/digest/.

Source file: DigestMD5Base.java

  19 
vote

/** 
 * Generates MAC to be appended onto out-going messages.
 * @param Ki A non-null byte array containing the key for the digest
 * @param seqnum A non-null byte array contain the sequence number
 * @param msg  The message to be digested
 * @param start The offset from which to read the msg byte array
 * @param len The non-zero number of bytes to be read from the offset
 * @return The MAC of a message.
 * @throws javax.security.sasl.SaslException if an error occurs when generating MAC.
 */
protected byte[] getHMAC(byte[] Ki,byte[] seqnum,byte[] msg,int start,int len) throws SaslException {
  byte[] seqAndMsg=new byte[4 + len];
  System.arraycopy(seqnum,0,seqAndMsg,0,4);
  System.arraycopy(msg,start,seqAndMsg,4,len);
  try {
    SecretKey keyKi=new SecretKeySpec(Ki,"HmacMD5");
    Mac m=Mac.getInstance("HmacMD5");
    m.init(keyKi);
    m.update(seqAndMsg);
    byte[] hMAC_MD5=m.doFinal();
    byte macBuffer[]=new byte[10];
    System.arraycopy(hMAC_MD5,0,macBuffer,0,10);
    return macBuffer;
  }
 catch (  InvalidKeyException e) {
    throw new SaslException("DIGEST-MD5: Invalid bytes used for " + "key of HMAC-MD5 hash.",e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new SaslException("DIGEST-MD5: Error creating " + "instance of MD5 digest algorithm",e);
  }
}
 

Example 41

From project jentrata-msh, under directory /Ext/ebxml-pkg/src/main/java/hk/hku/cecid/ebms/pkg/pki/.

Source file: CertSource.java

  19 
vote

/** 
 * Verifies whether the certificate is signed by the private key  corresponding to the specified public key.
 * @param pubKey the public key for verification
 * @return true if the verification is passed, false if otherwise.
 */
public boolean verify(PublicKey pubKey) throws InitializationException {
  if (x509Cert == null) {
    throw new InitializationException("Not yet initialized.");
  }
  boolean ret=false;
  try {
    x509Cert.verify(pubKey);
    ret=true;
  }
 catch (  CertificateException e) {
  }
catch (  NoSuchAlgorithmException e) {
  }
catch (  InvalidKeyException e) {
  }
catch (  NoSuchProviderException e) {
  }
catch (  SignatureException e) {
  }
  return ret;
}
 

Example 42

From project jftp, under directory /src/main/java/com/myjavaworld/jftp/.

Source file: FavoritesManager.java

  19 
vote

private static Cipher getCipher(int mode){
  final byte[] encodedKey={28,-9,-23,35,-93,-47,-28,55,-83,-82,101,-79,36,59,77,-121};
  Cipher cipher=null;
  try {
    cipher=Cipher.getInstance("AES");
    SecretKeySpec spec=new SecretKeySpec(encodedKey,"AES");
    cipher.init(mode,spec);
    return cipher;
  }
 catch (  InvalidKeyException exp) {
    exp.printStackTrace();
  }
catch (  NoSuchAlgorithmException exp) {
    exp.printStackTrace();
  }
catch (  NoSuchPaddingException exp) {
    exp.printStackTrace();
  }
  return null;
}
 

Example 43

From project JGit, under directory /org.spearce.jgit/src/org/spearce/jgit/transport/.

Source file: AmazonS3.java

  19 
vote

private void authorize(final HttpURLConnection c) throws IOException {
  final Map<String,List<String>> reqHdr=c.getRequestProperties();
  final SortedMap<String,String> sigHdr=new TreeMap<String,String>();
  for (  final Map.Entry<String,List<String>> entry : reqHdr.entrySet()) {
    final String hdr=entry.getKey();
    if (isSignedHeader(hdr))     sigHdr.put(hdr.toLowerCase(),toCleanString(entry.getValue()));
  }
  final StringBuilder s=new StringBuilder();
  s.append(c.getRequestMethod());
  s.append('\n');
  s.append(remove(sigHdr,"content-md5"));
  s.append('\n');
  s.append(remove(sigHdr,"content-type"));
  s.append('\n');
  s.append(remove(sigHdr,"date"));
  s.append('\n');
  for (  final Map.Entry<String,String> e : sigHdr.entrySet()) {
    s.append(e.getKey());
    s.append(':');
    s.append(e.getValue());
    s.append('\n');
  }
  final String host=c.getURL().getHost();
  s.append('/');
  s.append(host.substring(0,host.length() - DOMAIN.length() - 1));
  s.append(c.getURL().getPath());
  final String sec;
  try {
    final Mac m=Mac.getInstance(HMAC);
    m.init(privateKey);
    sec=Base64.encodeBytes(m.doFinal(s.toString().getBytes("UTF-8")));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IOException("No " + HMAC + " support:"+ e.getMessage());
  }
catch (  InvalidKeyException e) {
    throw new IOException("Invalid key: " + e.getMessage());
  }
  c.setRequestProperty("Authorization","AWS " + publicKey + ":"+ sec);
}
 

Example 44

From project jmeter-components, under directory /src/main/java/com/atlantbh/jmeter/plugins/oauth/.

Source file: OAuthGenerator.java

  19 
vote

private Mac getMac(String consumerSecret){
  try {
    SecretKey key=new SecretKeySpec((consumerSecret + '&').getBytes(UTF_8),MAC_NAME);
    Mac result=Mac.getInstance(MAC_NAME);
    result.init(key);
    return result;
  }
 catch (  UnsupportedEncodingException e) {
    log.log(Level.SEVERE,"This exception should never ocurr!",e);
  }
catch (  NoSuchAlgorithmException e) {
    log.log(Level.SEVERE,"This exception should never ocurr!",e);
  }
catch (  InvalidKeyException e) {
    log.log(Level.SEVERE,"The key used to initialize MAC algorithm is invalid.",e);
  }
  return null;
}
 

Example 45

From project Jota-Text-Editor, under directory /src/jp/sblo/pandora/billing/.

Source file: Security.java

  19 
vote

/** 
 * Verifies that the signature from the server matches the computed signature on the data.  Returns true if the data is correctly signed.
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey,String signedData,String signature){
  if (Consts.DEBUG) {
    Log.i(TAG,"signature: " + signature);
  }
  Signature sig;
  try {
    sig=Signature.getInstance(SIGNATURE_ALGORITHM);
    sig.initVerify(publicKey);
    sig.update(signedData.getBytes());
    if (!sig.verify(Base64.decode(signature))) {
      Log.e(TAG,"Signature verification failed.");
      return false;
    }
    return true;
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(TAG,"NoSuchAlgorithmException.");
  }
catch (  InvalidKeyException e) {
    Log.e(TAG,"Invalid key specification.");
  }
catch (  SignatureException e) {
    Log.e(TAG,"Signature exception.");
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
  }
  return false;
}
 

Example 46

From project jPOS, under directory /jpos/src/main/java/org/jpos/security/jceadapter/.

Source file: JCEHandler.java

  19 
vote

/** 
 * Helper method used for create or retrieve MAC algorithm from cache
 * @param engine object identyifing MAC algorithm
 * @return Initialized MAC algotithm
 * @throws org.jpos.security.jceadapter.JCEHandlerException
 */
Mac assignMACEngine(MacEngineKey engine) throws JCEHandlerException {
  if (macEngines.containsKey(engine)) {
    return macEngines.get(engine);
  }
  Mac mac=null;
  try {
    mac=Mac.getInstance(engine.getMacAlgorithm(),provider);
    mac.init(engine.getMacKey());
  }
 catch (  NoSuchAlgorithmException e) {
    throw new JCEHandlerException(e);
  }
catch (  InvalidKeyException e) {
    throw new JCEHandlerException(e);
  }
  macEngines.put(engine,mac);
  return mac;
}
 

Example 47

From project jsecurity, under directory /core/src/main/java/org/apache/ki/crypto/.

Source file: BlowfishCipher.java

  19 
vote

/** 
 * Initializes the JDK Cipher with the specified mode and key.  This is primarily a utility method to catch any potential  {@link InvalidKeyException InvalidKeyException} that might arise.
 * @param cipher the JDK Cipher to {@link javax.crypto.Cipher#init(int,java.security.Key) init}.
 * @param mode   the Cipher mode
 * @param key    the Cipher's Key
 */
protected void init(javax.crypto.Cipher cipher,int mode,java.security.Key key){
  try {
    cipher.init(mode,key);
  }
 catch (  InvalidKeyException e) {
    String msg="Unable to init cipher.";
    throw new IllegalStateException(msg,e);
  }
}
 

Example 48

From project Karotz-Plugin, under directory /src/main/java/org/jenkinsci/plugins/karotz/.

Source file: KarotzUtil.java

  19 
vote

/** 
 * Creates HmacSha1.
 * @param secretKey SecretKey
 * @param data target data
 * @return HmacSha1
 * @throws KarotzException Illegal encoding.
 */
public static String doHmacSha1(String secretKey,String data) throws KarotzException {
  String hmacSha1;
  try {
    Mac mac=Mac.getInstance("HmacSHA1");
    SecretKeySpec secret=new SecretKeySpec(secretKey.getBytes("ASCII"),"HmacSHA1");
    mac.init(secret);
    byte[] digest=mac.doFinal(data.getBytes("UTF-8"));
    hmacSha1=new String(Base64.encodeBase64(digest),"ASCII");
  }
 catch (  IllegalStateException e) {
    throw new KarotzException(e);
  }
catch (  InvalidKeyException e) {
    throw new KarotzException(e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new KarotzException(e);
  }
catch (  UnsupportedEncodingException e) {
    throw new KarotzException(e);
  }
  return hmacSha1;
}
 

Example 49

From project mapfish-print, under directory /src/main/java/org/mapfish/print/map/readers/google/.

Source file: GoogleConfig.java

  19 
vote

URI signURI(URI uri) throws UnsupportedEncodingException, URISyntaxException {
  try {
    String[] path=uri.toString().substring(uri.toString().indexOf(uri.getPath())).split("#",2);
    String signedURI=uri.toString() + "&signature=" + signer.signature(path[0]);
    if (path.length > 1) {
      signedURI+=path[1];
    }
    return new URI(signedURI);
  }
 catch (  InvalidKeyException e) {
    throw new RuntimeException(e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 

Example 50

From project mapfish-print_1, under directory /src/main/java/org/mapfish/print/map/readers/google/.

Source file: GoogleConfig.java

  19 
vote

URI signURI(URI uri) throws UnsupportedEncodingException, URISyntaxException {
  try {
    String[] path=uri.toString().substring(uri.toString().indexOf(uri.getPath())).split("#",2);
    String signedURI=uri.toString() + "&signature=" + signer.signature(path[0]);
    if (path.length > 1) {
      signedURI+=path[1];
    }
    return new URI(signedURI);
  }
 catch (  InvalidKeyException e) {
    throw new RuntimeException(e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 

Example 51

From project milton, under directory /milton/milton-client-app/src/main/java/bradswebdavclient/.

Source file: StringEncrypter.java

  19 
vote

public StringEncrypter(String encryptionScheme,String encryptionKey) throws EncryptionException {
  if (encryptionKey == null)   throw new IllegalArgumentException("encryption key was null");
  if (encryptionKey.trim().length() < 24)   throw new IllegalArgumentException("encryption key was less than 24 characters");
  try {
    byte[] keyAsBytes=encryptionKey.getBytes(UNICODE_FORMAT);
    if (encryptionScheme.equals(DESEDE_ENCRYPTION_SCHEME)) {
      keySpec=new DESedeKeySpec(keyAsBytes);
    }
 else     if (encryptionScheme.equals(DES_ENCRYPTION_SCHEME)) {
      keySpec=new DESKeySpec(keyAsBytes);
    }
 else {
      throw new IllegalArgumentException("Encryption scheme not supported: " + encryptionScheme);
    }
    keyFactory=SecretKeyFactory.getInstance(encryptionScheme);
    cipher=Cipher.getInstance(encryptionScheme);
  }
 catch (  InvalidKeyException e) {
    throw new EncryptionException(e);
  }
catch (  UnsupportedEncodingException e) {
    throw new EncryptionException(e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new EncryptionException(e);
  }
catch (  NoSuchPaddingException e) {
    throw new EncryptionException(e);
  }
}
 

Example 52

From project milton2, under directory /milton-client-app/src/main/java/bradswebdavclient/.

Source file: StringEncrypter.java

  19 
vote

public StringEncrypter(String encryptionScheme,String encryptionKey) throws EncryptionException {
  if (encryptionKey == null)   throw new IllegalArgumentException("encryption key was null");
  if (encryptionKey.trim().length() < 24)   throw new IllegalArgumentException("encryption key was less than 24 characters");
  try {
    byte[] keyAsBytes=encryptionKey.getBytes(UNICODE_FORMAT);
    if (encryptionScheme.equals(DESEDE_ENCRYPTION_SCHEME)) {
      keySpec=new DESedeKeySpec(keyAsBytes);
    }
 else     if (encryptionScheme.equals(DES_ENCRYPTION_SCHEME)) {
      keySpec=new DESKeySpec(keyAsBytes);
    }
 else {
      throw new IllegalArgumentException("Encryption scheme not supported: " + encryptionScheme);
    }
    keyFactory=SecretKeyFactory.getInstance(encryptionScheme);
    cipher=Cipher.getInstance(encryptionScheme);
  }
 catch (  InvalidKeyException e) {
    throw new EncryptionException(e);
  }
catch (  UnsupportedEncodingException e) {
    throw new EncryptionException(e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new EncryptionException(e);
  }
catch (  NoSuchPaddingException e) {
    throw new EncryptionException(e);
  }
}
 

Example 53

From project mina-sshd, under directory /sshd-core/src/main/java/org/apache/sshd/.

Source file: SshClient.java

  19 
vote

private static void setUpDefaultCiphers(SshClient client){
  List<NamedFactory<Cipher>> avail=new LinkedList<NamedFactory<Cipher>>();
  avail.add(new AES128CTR.Factory());
  avail.add(new AES256CTR.Factory());
  avail.add(new ARCFOUR128.Factory());
  avail.add(new ARCFOUR256.Factory());
  avail.add(new AES128CBC.Factory());
  avail.add(new TripleDESCBC.Factory());
  avail.add(new BlowfishCBC.Factory());
  avail.add(new AES192CBC.Factory());
  avail.add(new AES256CBC.Factory());
  for (Iterator<NamedFactory<Cipher>> i=avail.iterator(); i.hasNext(); ) {
    final NamedFactory<Cipher> f=i.next();
    try {
      final Cipher c=f.create();
      final byte[] key=new byte[c.getBlockSize()];
      final byte[] iv=new byte[c.getIVSize()];
      c.init(Cipher.Mode.Encrypt,key,iv);
    }
 catch (    InvalidKeyException e) {
      i.remove();
    }
catch (    Exception e) {
      i.remove();
    }
  }
  client.setCipherFactories(avail);
}
 

Example 54

From project Monetizing-Android-Demo-Project, under directory /src/dk/trifork/geeknight/billing/.

Source file: Security.java

  19 
vote

/** 
 * Verifies that the signature from the server matches the computed signature on the data.  Returns true if the data is correctly signed.
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey,String signedData,String signature){
  Signature sig;
  try {
    sig=Signature.getInstance(SIGNATURE_ALGORITHM);
    sig.initVerify(publicKey);
    sig.update(signedData.getBytes());
    if (!sig.verify(Base64.decode(signature))) {
      Log.e(TAG,"Signature verification failed.");
      return false;
    }
    return true;
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(TAG,"NoSuchAlgorithmException.");
  }
catch (  InvalidKeyException e) {
    Log.e(TAG,"Invalid key specification.");
  }
catch (  SignatureException e) {
    Log.e(TAG,"Signature exception.");
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
  }
  return false;
}
 

Example 55

From project nevernote, under directory /src/cx/fbn/nevernote/evernote/.

Source file: EnCrypt.java

  19 
vote

public String encrypt(String text,String passphrase,int keylen){
  RC2ParameterSpec parm=new RC2ParameterSpec(keylen);
  try {
    MessageDigest md=MessageDigest.getInstance("MD5");
    md.update(passphrase.getBytes(getCharset()));
    SecretKeySpec skeySpec=new SecretKeySpec(md.digest(),"RC2");
    Cipher cipher=Cipher.getInstance("RC2/ECB/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE,skeySpec,parm);
    byte[] newBytes=encodeStringNew(text);
    byte[] d=cipher.doFinal(newBytes);
    return Base64.encodeBytes(d);
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
catch (  NoSuchPaddingException e) {
    e.printStackTrace();
  }
catch (  InvalidKeyException e) {
    e.printStackTrace();
  }
catch (  InvalidAlgorithmParameterException e) {
    e.printStackTrace();
  }
catch (  IllegalBlockSizeException e) {
    e.printStackTrace();
  }
catch (  BadPaddingException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 56

From project NFCShopping, under directory /mobile phone client/NFCShopping/src/weibo4android/http/.

Source file: OAuth.java

  19 
vote

/** 
 * Computes RFC 2104-compliant HMAC signature.
 * @param data the data to be signed
 * @return signature
 * @see <a href="http://oauth.net/core/1.0/#rfc.section.9.2.1">OAuth Core - 9.2.1.  Generating Signature</a>
 */
String generateSignature(String data,OAuthToken token){
  byte[] byteHMAC=null;
  try {
    Mac mac=Mac.getInstance(HMAC_SHA1);
    SecretKeySpec spec;
    if (null == token) {
      String oauthSignature=encode(consumerSecret) + "&";
      spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
    }
 else {
      if (null == token.getSecretKeySpec()) {
        String oauthSignature=encode(consumerSecret) + "&" + encode(token.getTokenSecret());
        spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
        token.setSecretKeySpec(spec);
      }
      spec=token.getSecretKeySpec();
    }
    mac.init(spec);
    byteHMAC=mac.doFinal(data.getBytes());
  }
 catch (  InvalidKeyException e) {
    e.printStackTrace();
  }
catch (  NoSuchAlgorithmException ignore) {
  }
  return new BASE64Encoder().encode(byteHMAC);
}
 

Example 57

From project nsi-minlog, under directory /functional-tests/src/test/java/dk/nsi/minlog/test/utils/.

Source file: SOSI.java

  19 
vote

public static IDCard getIDCardElement(boolean sign,SOSIFactory factory,CredentialVault vault,PersonAndCertificate person) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, IOException, ServiceException, ParserConfigurationException {
  CareProvider careProvider=new CareProvider(SubjectIdentifierTypeValues.CVR_NUMBER,person.getCvr(),"test");
  UserInfo userInfo=new UserInfo(person.getCpr(),person.getFirstName(),person.getLastName(),person.getEmail(),"test user","Doctor","000");
  IDCard card=factory.createNewUserIDCard("SOSITEST",userInfo,careProvider,AuthenticationLevel.MOCES_TRUSTED_USER,null,null,person.getCertificate(),null);
  if (sign) {
    card=signIdCard(factory,vault,card,person);
  }
  return card;
}
 

Example 58

From project OAuth2Android, under directory /src/org/gerstner/oauth2android/token/.

Source file: MacTokenTypeDefinition.java

  19 
vote

private static String calculateMAC(String key,String normalizedString,String algorithm){
  String macString="";
  try {
    System.out.println("algorithm=" + algorithm);
    Mac mac=Mac.getInstance(algorithm);
    mac.init(new SecretKeySpec(key.getBytes(),algorithm));
    macString=Base64.encodeToString(mac.doFinal(normalizedString.getBytes()),Base64.DEFAULT);
  }
 catch (  InvalidKeyException ex) {
    Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE,null,ex);
  }
catch (  NoSuchAlgorithmException ex) {
    Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE,null,ex);
  }
  return macString;
}
 

Example 59

From project obpro_team_p, under directory /twitter/twitter4j-core/src/main/java/twitter4j/auth/.

Source file: OAuthAuthorization.java

  19 
vote

/** 
 * Computes RFC 2104-compliant HMAC signature.
 * @param data  the data to be signed
 * @param token the token
 * @return signature
 * @see <a href="http://oauth.net/core/1.0a/#rfc.section.9.2.1">OAuth Core - 9.2.1.  Generating Signature</a>
 */
String generateSignature(String data,OAuthToken token){
  byte[] byteHMAC=null;
  try {
    Mac mac=Mac.getInstance(HMAC_SHA1);
    SecretKeySpec spec;
    if (null == token) {
      String oauthSignature=HttpParameter.encode(consumerSecret) + "&";
      spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
    }
 else {
      spec=token.getSecretKeySpec();
      if (null == spec) {
        String oauthSignature=HttpParameter.encode(consumerSecret) + "&" + HttpParameter.encode(token.getTokenSecret());
        spec=new SecretKeySpec(oauthSignature.getBytes(),HMAC_SHA1);
        token.setSecretKeySpec(spec);
      }
    }
    mac.init(spec);
    byteHMAC=mac.doFinal(data.getBytes());
  }
 catch (  InvalidKeyException ike) {
    logger.error("Failed initialize \"Message Authentication Code\" (MAC)",ike);
    throw new AssertionError(ike);
  }
catch (  NoSuchAlgorithmException nsae) {
    logger.error("Failed to get HmacSHA1 \"Message Authentication Code\" (MAC)",nsae);
    throw new AssertionError(nsae);
  }
  return BASE64Encoder.encode(byteHMAC);
}
 

Example 60

From project Ohmage_Phone, under directory /src/org/ccnx/android/ccnlib/.

Source file: CCNxConfiguration.java

  19 
vote

public static void createUserKeystore(File user_dir,String user_name,String keystore_name,String keystore_password) throws ConfigurationException, IOException, InvalidKeyException {
  BasicKeyManager bkm=new BasicKeyManager(user_name,user_dir.getAbsolutePath(),null,keystore_name,null,null,null == keystore_password ? null : keystore_password.toCharArray());
  Log.i(TAG,"Initializing BKM");
  bkm.initialize();
  Log.i(TAG,"Closing BKM");
  bkm.close();
}
 

Example 61

From project onebusaway-nyc, under directory /onebusaway-nyc-presentation/src/main/java/org/onebusaway/nyc/geocoder/impl/.

Source file: GoogleGeocoderImpl.java

  19 
vote

/** 
 * PRIVATE METHODS
 */
private String signRequest(String key,String resource) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException {
  key=key.replace('-','+');
  key=key.replace('_','/');
  byte[] base64edKey=Base64.decodeBase64(key.getBytes());
  SecretKeySpec sha1Key=new SecretKeySpec(base64edKey,"HmacSHA1");
  Mac mac=Mac.getInstance("HmacSHA1");
  mac.init(sha1Key);
  byte[] sigBytes=mac.doFinal(resource.getBytes());
  String signature=new String(Base64.encodeBase64(sigBytes));
  signature=signature.replace('+','-');
  signature=signature.replace('/','_');
  return resource + "&signature=" + signature;
}
 

Example 62

From project Openbravo-POS-iPhone-App, under directory /OpenbravoPOS_PDA/src-pda/com/openbravo/pos/pda/util/.

Source file: CryptUtils.java

  19 
vote

/** 
 * Creates a new instance of Encrypter 
 */
public CryptUtils(String passPhrase){
  try {
    SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(passPhrase.getBytes("UTF8"));
    KeyGenerator kGen=KeyGenerator.getInstance("DESEDE");
    kGen.init(168,sr);
    Key key=kGen.generateKey();
    cipherDecrypt=Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
    cipherDecrypt.init(Cipher.DECRYPT_MODE,key);
  }
 catch (  UnsupportedEncodingException e) {
  }
catch (  NoSuchPaddingException e) {
  }
catch (  NoSuchAlgorithmException e) {
  }
catch (  InvalidKeyException e) {
  }
}
 

Example 63

From project OpenID-Connect-Java-Spring-Server, under directory /openid-connect-common/src/main/java/org/mitre/jwt/encryption/impl/.

Source file: RsaDecrypter.java

  19 
vote

@Override public Jwe decrypt(String encryptedJwe) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
  Jwe jwe=Jwe.parse(encryptedJwe);
  String alg=jwe.getHeader().getAlgorithm();
  if (alg.equals("RSA1_5") || alg.equals("RSA-OAEP")) {
    jwe.setEncryptedKey(decryptEncryptionKey(jwe));
    byte[] contentEncryptionKey=null;
    String kdf=jwe.getHeader().getKeyDerivationFunction();
    String keyLength=JweAlgorithms.getByName(kdf);
    int keyBitLength=Integer.parseInt(keyLength);
    contentEncryptionKey=generateContentKey(jwe.getEncryptedKey(),keyBitLength,"Encryption".getBytes());
    jwe.setCiphertext(decryptCipherText(jwe,contentEncryptionKey));
  }
 else {
    throw new IllegalArgumentException(jwe.getHeader().getEncryptionMethod() + " is not a valid decrypting algorithm");
  }
  return jwe;
}
 

Example 64

From project pdftk, under directory /java/com/lowagie/text/pdf/.

Source file: PdfPKCS7.java

  19 
vote

/** 
 * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
 * @param contentsKey the /Contents key
 * @param certsKey the /Cert key
 * @param provider the provider or <code>null</code> for the default provider
 * @throws SecurityException on error
 * @throws CRLException on error
 * @throws InvalidKeyException on error
 * @throws CertificateException on error
 * @throws NoSuchProviderException on error
 * @throws NoSuchAlgorithmException on error
 * @throws IOException on error
 */
public PdfPKCS7(byte[] contentsKey,byte[] certsKey,String provider) throws SecurityException, CRLException, InvalidKeyException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException {
  CertificateFactory cf;
  if (provider == null)   cf=CertificateFactory.getInstance("X.509");
 else   cf=CertificateFactory.getInstance("X.509",provider);
  if (provider == null)   certs=cf.generateCertificates(new ByteArrayInputStream(certsKey));
  signCert=(X509Certificate)certs.iterator().next();
  crls=new ArrayList();
  ASN1InputStream in=new ASN1InputStream(new ByteArrayInputStream(contentsKey));
  digest=((DEROctetString)in.readObject()).getOctets();
  if (provider == null)   sig=Signature.getInstance("SHA1withRSA");
 else   sig=Signature.getInstance("SHA1withRSA",provider);
  sig.initVerify(signCert.getPublicKey());
}
 

Example 65

From project picketbox-keystore, under directory /src/main/java/org/picketbox/keystore/util/.

Source file: KeyStoreDBUtil.java

  19 
vote

public static String saltedHmacMD5(String salt,byte[] data) throws InvalidKeyException, NoSuchAlgorithmException {
  MessageDigest digest=MessageDigest.getInstance("MD5");
  digest.update(data,0,data.length);
  String md5=new BigInteger(1,digest.digest()).toString(16);
  return md5 + salt;
}
 

Example 66

From project playn, under directory /payments/server/src/playn/payments/server/.

Source file: JWTEncodedServiceImp.java

  19 
vote

private JsonToken createToken(String iat,String exp,PurchaseRequest purchaseRequest) throws InvalidKeyException, NullPurchaseMetaDataException {
  Calendar cal=Calendar.getInstance();
  HmacSHA256Signer signer=new HmacSHA256Signer(iss,null,secret.getBytes());
  JsonToken token=new JsonToken(signer);
  token.setAudience(aud);
  token.setParam("typ",typ);
  if (iat == null) {
    token.setIssuedAt(new Instant(cal.getTimeInMillis()));
  }
 else {
    token.setIssuedAt(new Instant(Long.parseLong(iat)));
  }
  if (exp == null) {
    token.setExpiration(new Instant(cal.getTimeInMillis() + timespan));
  }
 else {
    token.setExpiration(new Instant(Long.parseLong(exp)));
  }
  JsonObject request=new JsonObject();
  request.addProperty("name",purchaseRequest.name());
  request.addProperty("description",purchaseRequest.description());
  request.addProperty("price",purchaseRequest.price());
  request.addProperty("currencyCode",purchaseRequest.currencyCode());
  request.addProperty("sellerData",purchaseRequest.sellerData());
  JsonObject payload=token.getPayloadAsJsonObject();
  payload.add("request",request);
  return token;
}
 

Example 67

From project QuotaForAndroid, under directory /Quota/src/com/southfreo/quota/billing/.

Source file: Security.java

  19 
vote

/** 
 * Verifies that the signature from the server matches the computed signature on the data.  Returns true if the data is correctly signed.
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey,String signedData,String signature){
  if (Consts.DEBUG) {
    Log.i(TAG,"signature: " + signature);
  }
  Signature sig;
  try {
    sig=Signature.getInstance(SIGNATURE_ALGORITHM);
    sig.initVerify(publicKey);
    sig.update(signedData.getBytes());
    if (!sig.verify(Base64.decode(signature))) {
      Log.e(TAG,"Signature verification failed.");
      return false;
    }
    return true;
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(TAG,"NoSuchAlgorithmException.");
  }
catch (  InvalidKeyException e) {
    Log.e(TAG,"Invalid key specification.");
  }
catch (  SignatureException e) {
    Log.e(TAG,"Signature exception.");
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
  }
  return false;
}
 

Example 68

From project recordloader, under directory /src/java/com/marklogic/ps/.

Source file: JEncryption.java

  19 
vote

public static void main(String[] argv){
  try {
    KeyGenerator keygenerator=KeyGenerator.getInstance("DES");
    SecretKey myDesKey=keygenerator.generateKey();
    Cipher desCipher;
    desCipher=Cipher.getInstance("DES/ECB/PKCS5Padding");
    desCipher.init(Cipher.ENCRYPT_MODE,myDesKey);
    byte[] text="No body can see me".getBytes();
    System.out.println("Text [Byte Format] : " + text);
    System.out.println("Text : " + new String(text));
    byte[] textEncrypted=desCipher.doFinal(text);
    System.out.println("Text Encryted : " + textEncrypted);
    desCipher.init(Cipher.DECRYPT_MODE,myDesKey);
    byte[] textDecrypted=desCipher.doFinal(textEncrypted);
    System.out.println("Text Decryted : " + new String(textDecrypted));
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
catch (  NoSuchPaddingException e) {
    e.printStackTrace();
  }
catch (  InvalidKeyException e) {
    e.printStackTrace();
  }
catch (  IllegalBlockSizeException e) {
    e.printStackTrace();
  }
catch (  BadPaddingException e) {
    e.printStackTrace();
  }
}
 

Example 69

From project Red5, under directory /src/org/red5/server/net/rtmp/.

Source file: RTMPHandshake.java

  19 
vote

/** 
 * Calculates an HMAC SHA256 hash using a default key length.
 * @param input
 * @param key
 * @return hmac hashed bytes
 */
public byte[] calculateHMAC_SHA256(byte[] input,byte[] key){
  byte[] output=null;
  try {
    hmacSHA256.init(new SecretKeySpec(key,"HmacSHA256"));
    output=hmacSHA256.doFinal(input);
  }
 catch (  InvalidKeyException e) {
    log.error("Invalid key",e);
  }
  return output;
}
 

Example 70

From project red5-mavenized, under directory /red5_base/src/main/java/org/red5/server/net/rtmp/.

Source file: RTMPHandshake.java

  19 
vote

public byte[] calculateHMAC_SHA256(byte[] input,byte[] key){
  byte[] output=null;
  try {
    hmacSHA256.init(new SecretKeySpec(key,"HmacSHA256"));
    output=hmacSHA256.doFinal(input);
  }
 catch (  InvalidKeyException e) {
    log.error("Invalid key",e);
  }
  return output;
}
 

Example 71

From project red5-server, under directory /src/org/red5/server/net/rtmp/.

Source file: RTMPHandshake.java

  19 
vote

/** 
 * Calculates an HMAC SHA256 hash using a default key length.
 * @param input
 * @param key
 * @return hmac hashed bytes
 */
public byte[] calculateHMAC_SHA256(byte[] input,byte[] key){
  byte[] output=null;
  try {
    hmacSHA256.init(new SecretKeySpec(key,"HmacSHA256"));
    output=hmacSHA256.doFinal(input);
  }
 catch (  InvalidKeyException e) {
    log.error("Invalid key",e);
  }
  return output;
}
 

Example 72

From project safe, under directory /Safe/src/org/openintents/safe/.

Source file: CryptoHelper.java

  19 
vote

/** 
 * encrypt a string
 * @param plaintext
 * @return encrypted String
 * @throws Exception
 */
public String encrypt(String plaintext) throws CryptoHelperException {
  status=false;
  if (password == null) {
    String msg="Must call setPassword before running encrypt.";
    throw new CryptoHelperException(msg);
  }
  if (salt == null) {
    String msg="Must call setSalt before running encrypt.";
    throw new CryptoHelperException(msg);
  }
  byte[] ciphertext={};
  if (plaintext == null) {
    return "";
  }
  try {
    pbeCipher.init(Cipher.ENCRYPT_MODE,pbeKey,pbeParamSpec);
    ciphertext=pbeCipher.doFinal(plaintext.getBytes());
    status=true;
  }
 catch (  IllegalBlockSizeException e) {
    Log.e(TAG,"encrypt(): " + e.toString());
  }
catch (  BadPaddingException e) {
    Log.e(TAG,"encrypt(): " + e.toString());
  }
catch (  InvalidKeyException e) {
    Log.e(TAG,"encrypt(): " + e.toString());
  }
catch (  InvalidAlgorithmParameterException e) {
    Log.e(TAG,"encrypt(): " + e.toString());
  }
  String stringCiphertext=toHexString(ciphertext);
  return stringCiphertext;
}
 

Example 73

From project sauce-ondemand-plugin, under directory /src/main/java/hudson/plugins/sauce_ondemand/.

Source file: SauceOnDemandReport.java

  19 
vote

public String getAuth() throws IOException {
  try {
    Calendar calendar=Calendar.getInstance();
    SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd-HH");
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    String key=PluginImpl.get().getUsername() + ":" + PluginImpl.get().getApiKey()+ ":"+ format.format(calendar.getTime());
    byte[] keyBytes=key.getBytes();
    SecretKeySpec sks=new SecretKeySpec(keyBytes,HMAC_KEY);
    Mac mac=Mac.getInstance(sks.getAlgorithm());
    mac.init(sks);
    byte[] hmacBytes=mac.doFinal(id.getBytes());
    byte[] hexBytes=new Hex().encode(hmacBytes);
    return new String(hexBytes,"ISO-8859-1");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IOException("Could not generate Sauce-OnDemand access code",e);
  }
catch (  InvalidKeyException e) {
    throw new IOException("Could not generate Sauce-OnDemand access code",e);
  }
catch (  UnsupportedEncodingException e) {
    throw new IOException("Could not generate Sauce-OnDemand access code",e);
  }
}
 

Example 74

From project Schedule, under directory /android/src/com/happytap/schedule/service/.

Source file: Security.java

  19 
vote

/** 
 * Verifies that the signature from the server matches the computed signature on the data.  Returns true if the data is correctly signed.
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey,String signedData,String signature){
  if (Consts.DEBUG) {
    Log.i(TAG,"signature: " + signature);
  }
  Signature sig;
  try {
    sig=Signature.getInstance(SIGNATURE_ALGORITHM);
    sig.initVerify(publicKey);
    sig.update(signedData.getBytes());
    if (!sig.verify(Base64.decode(signature))) {
      Log.e(TAG,"Signature verification failed.");
      return false;
    }
    return true;
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(TAG,"NoSuchAlgorithmException.");
  }
catch (  InvalidKeyException e) {
    Log.e(TAG,"Invalid key specification.");
  }
catch (  SignatureException e) {
    Log.e(TAG,"Signature exception.");
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
  }
  return false;
}
 

Example 75

From project security, under directory /impl/src/main/java/org/jboss/seam/security/crypto/.

Source file: MacBasedPRF.java

  19 
vote

public void init(byte[] P){
  try {
    mac.init(new SecretKeySpec(P,macAlgorithm));
  }
 catch (  InvalidKeyException e) {
    throw new RuntimeException(e);
  }
}
 

Example 76

From project skmclauncher, under directory /src/main/java/com/sk89q/mclauncher/.

Source file: Launcher.java

  19 
vote

/** 
 * Get a cipher.
 * @param mode cipher mode (see {@link Cipher} constants)
 * @param password password
 * @return cipher
 * @throws InvalidKeySpecException on cipher error
 * @throws NoSuchAlgorithmException on cipher error
 * @throws NoSuchPaddingException on cipher error
 * @throws InvalidKeyException on cipher error
 * @throws InvalidAlgorithmParameterException on cipher error
 */
public Cipher getCipher(int mode,String password) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
  Random random=new Random(0x29482c2L);
  byte salt[]=new byte[8];
  random.nextBytes(salt);
  PBEParameterSpec paramSpec=new PBEParameterSpec(salt,5);
  SecretKeyFactory factory=SecretKeyFactory.getInstance("PBEWithMD5AndDES");
  SecretKey key=factory.generateSecret(new PBEKeySpec(password.toCharArray()));
  Cipher cipher=Cipher.getInstance("PBEWithMD5AndDES");
  cipher.init(mode,key,paramSpec);
  return cipher;
}
 

Example 77

From project sonet, under directory /core/src/com/piusvelte/sonet/core/.

Source file: SonetCrypto.java

  19 
vote

protected String Decrypt(String data){
  if ((mSecretKey != null) && (data != null)) {
    try {
      Cipher cipher=Cipher.getInstance("AES");
      cipher.init(Cipher.DECRYPT_MODE,mSecretKey);
      return new String(cipher.doFinal(Base64.decode(data,Base64.DEFAULT)),"UTF-8");
    }
 catch (    NoSuchAlgorithmException e) {
      Log.e(TAG,e.toString());
    }
catch (    NoSuchPaddingException e) {
      Log.e(TAG,e.toString());
    }
catch (    InvalidKeyException e) {
      Log.e(TAG,e.toString());
    }
catch (    IllegalBlockSizeException e) {
      Log.e(TAG,e.toString());
    }
catch (    BadPaddingException e) {
      Log.e(TAG,e.toString());
    }
catch (    UnsupportedEncodingException e) {
      Log.e(TAG,e.toString());
    }
  }
  return null;
}
 

Example 78

From project sparsemapcontent, under directory /core/src/main/java/org/sakaiproject/nakamura/lite/accesscontrol/.

Source file: PrincipalTokenValidator.java

  19 
vote

private String signToken(Content token,String sharedKey,PrincipalValidatorPlugin plugin){
  try {
    MessageDigest md=MessageDigest.getInstance("SHA-512");
    byte[] input=sharedKey.getBytes("UTF-8");
    byte[] data=md.digest(input);
    SecretKeySpec key=new SecretKeySpec(data,HMAC_SHA512);
    return getHmac(token,plugin.getProtectedFields(),key);
  }
 catch (  InvalidKeyException e) {
    LOGGER.warn(e.getMessage());
    LOGGER.debug(e.getMessage(),e);
    return null;
  }
catch (  NoSuchAlgorithmException e) {
    LOGGER.warn(e.getMessage());
    LOGGER.debug(e.getMessage(),e);
    return null;
  }
catch (  IllegalStateException e) {
    LOGGER.warn(e.getMessage());
    LOGGER.debug(e.getMessage(),e);
    return null;
  }
catch (  UnsupportedEncodingException e) {
    LOGGER.warn(e.getMessage());
    LOGGER.debug(e.getMessage(),e);
    return null;
  }
}
 

Example 79

From project spring-crypto-utils, under directory /src/main/java/com/springcryptoutils/core/mac/.

Source file: MacImpl.java

  19 
vote

public byte[] digest(byte[] message){
  try {
    final javax.crypto.Mac mac=(((provider == null) || (provider.length() == 0)) ? javax.crypto.Mac.getInstance(algorithm) : javax.crypto.Mac.getInstance(algorithm,provider));
    mac.init(secretKey);
    return mac.doFinal(message);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new MacException("no such algorithm: " + secretKey.getAlgorithm(),e);
  }
catch (  InvalidKeyException e) {
    throw new MacException("invalid key",e);
  }
catch (  NoSuchProviderException e) {
    throw new MacException("no such provider: " + provider,e);
  }
}
 

Example 80

From project spring-security, under directory /crypto/src/main/java/org/springframework/security/crypto/encrypt/.

Source file: CipherUtils.java

  19 
vote

/** 
 * Initializes the Cipher for use.
 */
public static void initCipher(Cipher cipher,int mode,SecretKey secretKey,AlgorithmParameterSpec parameterSpec){
  try {
    if (parameterSpec != null) {
      cipher.init(mode,secretKey,parameterSpec);
    }
 else {
      cipher.init(mode,secretKey);
    }
  }
 catch (  InvalidKeyException e) {
    throw new IllegalArgumentException("Unable to initialize due to invalid secret key",e);
  }
catch (  InvalidAlgorithmParameterException e) {
    throw new IllegalStateException("Unable to initialize due to invalid decryption parameter spec",e);
  }
}
 

Example 81

From project spring-security-oauth, under directory /spring-security-oauth/src/main/java/org/springframework/security/oauth/common/signature/.

Source file: HMAC_SHA1SignatureMethod.java

  19 
vote

/** 
 * Sign the signature base string. The signature is the digest octet string, first base64-encoded per RFC2045, section 6.8, then URL-encoded per OAuth Parameter Encoding.
 * @param signatureBaseString The signature base string.
 * @return The signature.
 */
public String sign(String signatureBaseString){
  try {
    Mac mac=Mac.getInstance(MAC_NAME);
    mac.init(key);
    byte[] text=signatureBaseString.getBytes("UTF-8");
    byte[] signatureBytes=mac.doFinal(text);
    signatureBytes=Base64.encodeBase64(signatureBytes);
    String signature=new String(signatureBytes,"UTF-8");
    if (LOG.isDebugEnabled()) {
      LOG.debug("signature base: " + signatureBaseString);
      LOG.debug("signature: " + signature);
    }
    return signature;
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
  }
catch (  InvalidKeyException e) {
    throw new IllegalStateException(e);
  }
catch (  UnsupportedEncodingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 82

From project spring-social, under directory /spring-social-core/src/main/java/org/springframework/social/oauth1/.

Source file: SigningSupport.java

  19 
vote

private String sign(String signatureBaseString,String key){
  try {
    Mac mac=Mac.getInstance(HMAC_SHA1_MAC_NAME);
    SecretKeySpec spec=new SecretKeySpec(key.getBytes(),HMAC_SHA1_MAC_NAME);
    mac.init(spec);
    byte[] text=signatureBaseString.getBytes(UTF8_CHARSET_NAME);
    byte[] signatureBytes=mac.doFinal(text);
    signatureBytes=Base64.encode(signatureBytes);
    String signature=new String(signatureBytes,UTF8_CHARSET_NAME);
    return signature;
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
  }
catch (  InvalidKeyException e) {
    throw new IllegalStateException(e);
  }
catch (  UnsupportedEncodingException shouldntHappen) {
    throw new IllegalStateException(shouldntHappen);
  }
}
 

Example 83

From project spring-social-facebook, under directory /spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/.

Source file: SignedRequestDecoder.java

  19 
vote

private byte[] encrypt(String base,String key){
  try {
    SecretKeySpec secretKeySpec=new SecretKeySpec(key.getBytes(),HMAC_SHA256_MAC_NAME);
    Mac mac=Mac.getInstance(HMAC_SHA256_MAC_NAME);
    mac.init(secretKeySpec);
    return mac.doFinal(base.getBytes());
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
  }
catch (  InvalidKeyException e) {
    throw new IllegalStateException(e);
  }
}
 

Example 84

From project stackmob-java-client-sdk, under directory /src/main/java/com/stackmob/sdk/api/.

Source file: StackMobSession.java

  19 
vote

public String generateMacToken(String method,String uri,String host,String port){
  String ts=String.valueOf(new Date().getTime() / 1000);
  String nonce=String.format("n%d",Math.round(Math.random() * 10000));
  try {
    String baseString=getNormalizedRequestString(ts,nonce,method,uri,host,port);
    Mac mac=Mac.getInstance(SIGNATURE_ALGORITHM);
    SecretKeySpec spec=new SecretKeySpec(oauth2MacKey.getBytes(),SIGNATURE_ALGORITHM);
    try {
      mac.init(spec);
    }
 catch (    InvalidKeyException ike) {
      throw new IllegalStateException(ike);
    }
    byte[] rawMacBytes=mac.doFinal(baseString.getBytes());
    byte[] b64Bytes=Base64.encodeBase64(rawMacBytes);
    String calculatedMac=new String(b64Bytes);
    return String.format("MAC id=\"%s\",ts=\"%s\",nonce=\"%s\",mac=\"%s\"",oauth2Token,ts,nonce,calculatedMac);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException("This device doesn't have SHA1");
  }
}
 

Example 85

From project syslog4j, under directory /src/main/java/com/nesscomputing/syslog4j/impl/message/modifier/mac/.

Source file: MacSyslogMessageModifier.java

  19 
vote

public MacSyslogMessageModifier(MacSyslogMessageModifierConfig config) throws SyslogRuntimeException {
  super(config);
  this.config=config;
  try {
    this.mac=Mac.getInstance(config.getMacAlgorithm());
    this.mac.init(config.getKey());
  }
 catch (  NoSuchAlgorithmException nsae) {
    throw new SyslogRuntimeException(nsae);
  }
catch (  InvalidKeyException ike) {
    throw new SyslogRuntimeException(ike);
  }
}
 

Example 86

From project TextSecure, under directory /src/org/thoughtcrime/securesms/crypto/.

Source file: DecryptingPartInputStream.java

  19 
vote

public DecryptingPartInputStream(File file,MasterSecret masterSecret) throws FileNotFoundException {
  super(file);
  try {
    if (file.length() <= IV_LENGTH + MAC_LENGTH)     throw new FileNotFoundException("Part shorter than crypto overhead!");
    done=false;
    mac=initializeMac(masterSecret.getMacKey());
    cipher=initializeCipher(masterSecret.getEncryptionKey());
    totalDataSize=file.length() - cipher.getBlockSize() - mac.getMacLength();
    totalRead=0;
  }
 catch (  InvalidKeyException ike) {
    Log.w("EncryptingPartInputStream",ike);
    throw new FileNotFoundException("Invalid key!");
  }
catch (  NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
catch (  InvalidAlgorithmParameterException e) {
    throw new AssertionError(e);
  }
catch (  NoSuchPaddingException e) {
    throw new AssertionError(e);
  }
catch (  IOException e) {
    Log.w("EncryptingPartInputStream",e);
    throw new FileNotFoundException("IOException while reading IV!");
  }
}
 

Example 87

From project thinklab, under directory /src/main/java/org/integratedmodelling/thinklab/authentication/.

Source file: EncryptionManager.java

  19 
vote

public EncryptionManager(String encryptionScheme,String encryptionKey) throws ThinklabValidationException {
  if (encryptionKey == null)   throw new IllegalArgumentException("encryption key was null");
  if (encryptionKey.trim().length() < 24)   throw new IllegalArgumentException("encryption key was less than 24 characters");
  try {
    byte[] keyAsBytes=encryptionKey.getBytes(UNICODE_FORMAT);
    if (encryptionScheme.equals(DESEDE_ENCRYPTION_SCHEME)) {
      keySpec=new DESedeKeySpec(keyAsBytes);
    }
 else     if (encryptionScheme.equals(DES_ENCRYPTION_SCHEME)) {
      keySpec=new DESKeySpec(keyAsBytes);
    }
 else {
      keySpec=new SecretKeySpec(keyAsBytes,encryptionKey);
    }
    keyFactory=SecretKeyFactory.getInstance(encryptionScheme);
    cipher=Cipher.getInstance(encryptionScheme);
  }
 catch (  InvalidKeyException e) {
    throw new ThinklabValidationException(e);
  }
catch (  UnsupportedEncodingException e) {
    throw new ThinklabValidationException(e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new ThinklabValidationException(e);
  }
catch (  NoSuchPaddingException e) {
    throw new ThinklabValidationException(e);
  }
}
 

Example 88

From project TomP2P, under directory /src/main/java/net/tomp2p/message/.

Source file: DataCodec.java

  19 
vote

public static Data decodeData(final ChannelBuffer buffer,PeerAddress originator) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
  if (buffer.readableBytes() < 4 + 4)   return null;
  int ttl=buffer.readInt();
  boolean protectedEntry=(ttl & 0x80000000) != 0;
  boolean fileReference=(ttl & 0x40000000) != 0;
  ttl&=0x3FFFFFFF;
  int dateLength=buffer.readInt();
  if (buffer.readableBytes() < dateLength)   return null;
  ByteBuffer[] byteBuffers=buffer.toByteBuffers(buffer.readerIndex(),dateLength);
  final Data data=createData(byteBuffers,dateLength,ttl,protectedEntry,fileReference,originator);
  buffer.skipBytes(dateLength);
  return data;
}