Java Code Examples for javax.crypto.spec.SecretKeySpec
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 BF3-Battlelog, under directory /src/net/sf/andhsli/hotspotlogin/.
Source file: SimpleCrypto.java

private static byte[] encrypt(byte[] raw,byte[] clear) throws Exception { SecretKeySpec skeySpec=new SecretKeySpec(raw,"AES"); Cipher cipher=Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE,skeySpec); byte[] encrypted=cipher.doFinal(clear); return encrypted; }
Example 2
From project android-bankdroid, under directory /src/net/sf/andhsli/hotspotlogin/.
Source file: SimpleCrypto.java

private static byte[] encrypt(byte[] raw,byte[] clear) throws Exception { SecretKeySpec skeySpec=new SecretKeySpec(raw,"AES"); Cipher cipher=Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE,skeySpec); byte[] encrypted=cipher.doFinal(clear); return encrypted; }
Example 3
From project spring-security-oauth, under directory /spring-security-oauth/src/test/java/net/oauth/signature/.
Source file: TestGoogleCodeCompatibility.java

/** * tests compatibilty with the google code HMAC_SHA1 signature. */ @Test public void testHMAC_SHA1_1() throws Exception { HMAC_SHA1 theirMethod=new HMAC_SHA1(); String baseString="GET&http%3A%2F%2Flocalhost%3A8080%2Fgrailscrowd%2Foauth%2Frequest_token&oauth_consumer_key%3Dtonrconsumerkey%26oauth_nonce%3D1227967049787975000%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1227967049%26oauth_version%3D1.0"; theirMethod.setConsumerSecret("xxxxxx"); theirMethod.setTokenSecret(""); SecretKeySpec spec=new SecretKeySpec("xxxxxx&".getBytes("UTF-8"),HMAC_SHA1SignatureMethod.MAC_NAME); HMAC_SHA1SignatureMethod ourMethod=new HMAC_SHA1SignatureMethod(spec); String theirSignature=theirMethod.getSignature(baseString); String ourSignature=ourMethod.sign(baseString); assertEquals(theirSignature,ourSignature); }
Example 4
From project encfs-java, under directory /src/main/java/org/mrpdaemon/sec/encfs/.
Source file: EncFSCrypto.java

/** * 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 5
From project GeoBI, under directory /print/src/main/java/org/mapfish/print/map/readers/google/.
Source file: GoogleURLSigner.java

public String signature(String resource) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException { SecretKeySpec sha1Key=new SecretKeySpec(key,"HmacSHA1"); Mac mac=Mac.getInstance("HmacSHA1"); mac.init(sha1Key); byte[] sigBytes=mac.doFinal(resource.getBytes()); String signature=Base64.encodeBytes(sigBytes); signature=signature.replace('+','-'); signature=signature.replace('/','_'); return signature; }
Example 6
From project SeriesGuide, under directory /SeriesGuide/src/com/battlelancer/seriesguide/util/.
Source file: SimpleCrypto.java

private static byte[] encrypt(byte[] raw,byte[] clear) throws Exception { SecretKeySpec skeySpec=new SecretKeySpec(raw,"AES"); Cipher cipher=Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE,skeySpec); byte[] encrypted=cipher.doFinal(clear); return encrypted; }
Example 7
From project siena, under directory /source/src/main/java/siena/sdb/ws/.
Source file: SimpleDB.java

private String sign(String data,String key){ try { SecretKeySpec signingKey=new SecretKeySpec(key.getBytes(ENCODING),SIGNATURE_METHOD); Mac mac=Mac.getInstance(SIGNATURE_METHOD); mac.init(signingKey); byte[] rawHmac=mac.doFinal(data.getBytes(ENCODING)); return Base64.encodeBytes(rawHmac); } catch ( Exception e) { throw new RuntimeException(e); } }
Example 8
From project BombusLime, under directory /src/org/bombusim/sasl/.
Source file: SASL_ScramSha1.java

private Mac getHMAC(byte[] str){ try { SecretKeySpec secret=new SecretKeySpec(str,"HmacSHA1"); hmac.init(secret); } catch ( Exception e) { e.printStackTrace(); } return hmac; }
Example 9
From project connectbot, under directory /src/sk/vx/connectbot/util/.
Source file: PubkeyUtils.java

public static byte[] cipher(int mode,byte[] data,byte[] secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { SecretKeySpec secretKeySpec=new SecretKeySpec(sha256(secret),"AES"); Cipher c=Cipher.getInstance("AES"); c.init(mode,secretKeySpec); return c.doFinal(data); }
Example 10
From project droidparts, under directory /extra/src/org/droidparts/util/crypto/.
Source file: Crypter.java

private static byte[] encrypt(byte[] raw,byte[] clear) throws Exception { SecretKeySpec skeySpec=new SecretKeySpec(raw,"AES"); Cipher cipher=Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE,skeySpec); byte[] encrypted=cipher.doFinal(clear); return encrypted; }
Example 11
From project eucalyptus, under directory /clc/modules/axis2-transport/src/edu/ucsb/eucalyptus/transport/query/.
Source file: HMACQuerySecurityHandler.java

protected String checkSignature(final String queryKey,final String subject) throws QuerySecurityException { SecretKeySpec signingKey=new SecretKeySpec(queryKey.getBytes(),Hashes.Mac.HmacSHA1.toString()); try { Mac mac=Mac.getInstance(Hashes.Mac.HmacSHA1.toString()); mac.init(signingKey); byte[] rawHmac=mac.doFinal(subject.getBytes()); return Base64.encode(rawHmac).replaceAll("=",""); } catch ( Exception e) { LOG.error(e,e); throw new QuerySecurityException("Failed to compute signature"); } }
Example 12
From project JGlobus, under directory /ssl-proxies/src/main/java/org/globus/gsi/.
Source file: OpenSSLKey.java

/** * Decrypts the private key with given password. Does nothing if the key is not encrypted. * @param password password to decrypt the key with. * @throws GeneralSecurityException whenever an error occurs during decryption. */ public void decrypt(byte[] password) throws GeneralSecurityException { if (!isEncrypted()) { return; } byte[] enc=Base64.decode(this.encodedKey); SecretKeySpec key=getSecretKey(password,this.initializationVector.getIV()); Cipher cipher=getCipher(); cipher.init(Cipher.DECRYPT_MODE,key,this.initializationVector); enc=cipher.doFinal(enc); this.intKey=getKey(this.keyAlg,enc); this.keyData=enc; this.isEncrypted=false; this.encodedKey=null; }
Example 13
From project JMaNGOS, under directory /Auth/src/main/java/org/jmangos/auth/network/crypt/.
Source file: Crypt.java

/** * Gets the key. * @param EncryptionKey the encryption key * @param key the key * @return the key */ private byte[] getKey(final byte[] EncryptionKey,final byte[] key){ final SecretKeySpec ds=new SecretKeySpec(EncryptionKey,"HmacSHA1"); Mac m; try { m=Mac.getInstance("HmacSHA1"); m.init(ds); return m.doFinal(key); } catch ( final Exception e) { e.printStackTrace(); } return null; }
Example 14
From project mapfish-print, under directory /src/main/java/org/mapfish/print/map/readers/google/.
Source file: GoogleURLSigner.java

public String signature(String resource) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException { SecretKeySpec sha1Key=new SecretKeySpec(key,"HmacSHA1"); Mac mac=Mac.getInstance("HmacSHA1"); mac.init(sha1Key); byte[] sigBytes=mac.doFinal(resource.getBytes()); String signature=Base64.encodeBytes(sigBytes); signature=signature.replace('+','-'); signature=signature.replace('/','_'); return signature; }
Example 15
From project mapfish-print_1, under directory /src/main/java/org/mapfish/print/map/readers/google/.
Source file: GoogleURLSigner.java

public String signature(String resource) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException { SecretKeySpec sha1Key=new SecretKeySpec(key,"HmacSHA1"); Mac mac=Mac.getInstance("HmacSHA1"); mac.init(sha1Key); byte[] sigBytes=mac.doFinal(resource.getBytes()); String signature=Base64.encodeBytes(sigBytes); signature=signature.replace('+','-'); signature=signature.replace('/','_'); return signature; }
Example 16
From project mina-sshd, under directory /sshd-core/src/main/java/org/apache/sshd/common/mac/.
Source file: BaseMac.java

public void init(byte[] key) throws Exception { if (key.length > defbsize) { byte[] tmp=new byte[defbsize]; System.arraycopy(key,0,tmp,0,defbsize); key=tmp; } SecretKeySpec skey=new SecretKeySpec(key,algorithm); mac=SecurityUtils.getMac(algorithm); mac.init(skey); }
Example 17
From project miso-lims, under directory /core/src/main/java/uk/ac/bbsrc/tgac/miso/core/security/.
Source file: PasswordCodecService.java

/** * Encrypt a plaintext String using a hmac_sha1 salt * @param key of type String * @param plaintext of type String * @return String the encrypted String of the given plaintext String * @throws SignatureException when the HMAC is unable to be generated */ public synchronized String encryptHMACSHA1(String key,String plaintext) throws java.security.SignatureException { String result; try { SecretKeySpec signingKey=new SecretKeySpec(key.getBytes(),"HmacSHA1"); Mac mac=Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac=mac.doFinal(plaintext.getBytes()); result=new Base64().encodeToString(rawHmac); } catch ( Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
Example 18
From project Monetizing-Android-Demo-Project, under directory /src/dk/trifork/geeknight/bigredbutton/.
Source file: SimpleCrypto.java

private static byte[] encrypt(byte[] raw,byte[] clear) throws Exception { SecretKeySpec skeySpec=new SecretKeySpec(raw,"AES"); Cipher cipher=Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE,skeySpec); byte[] encrypted=cipher.doFinal(clear); return encrypted; }
Example 19
From project narya, under directory /core/src/main/java/com/threerings/presents/util/.
Source file: SecureUtil.java

/** * Creates our AES cipher. */ public static Cipher getAESCipher(int mode,byte[] key){ try { Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec aesKey=new SecretKeySpec(key,"AES"); cipher.init(mode,aesKey,IVPS); return cipher; } catch ( GeneralSecurityException gse) { log.warning("Failed to create cipher",gse); } return null; }
Example 20
From project ODE-X, under directory /runtime/src/main/java/org/apache/ode/runtime/exec/platform/.
Source file: NodeImpl.java

public static String encrypt(String b64EncKey,String cleartext) throws Exception { byte[] encKey=DatatypeConverter.parseBase64Binary(b64EncKey); SecretKeySpec key=new SecretKeySpec(encKey,"AES"); Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE,key); return DatatypeConverter.printBase64Binary(cipher.doFinal(cleartext.getBytes("UTF-8"))); }
Example 21
From project onebusaway-nyc, under directory /onebusaway-nyc-presentation/src/main/java/org/onebusaway/nyc/geocoder/impl/.
Source file: GoogleGeocoderImpl.java

/** * 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 22
From project openengsb-framework, under directory /components/util/src/test/java/org/openengsb/core/util/.
Source file: CipherUtilTest.java

@Test public void testEncryptSymmetricKeyWithPublicKey_shouldBeTheSameWhenDecryptedWithPrivateKey() throws Exception { SecretKey secretKey=CipherUtils.generateKey("AES",128); byte[] encoded=secretKey.getEncoded(); byte[] encryptedKey=CipherUtils.encrypt(encoded,generatedPublickey); byte[] decryptKey=CipherUtils.decrypt(encryptedKey,generatedPrivatekey); SecretKeySpec secretKeySpec=new SecretKeySpec(decryptKey,"AES"); assertThat(secretKeySpec,is(secretKey)); }
Example 23
From project QuotaForAndroid, under directory /Quota/src/com/southfreo/quota/utils/.
Source file: Security.java

private static byte[] encrypt(byte[] raw,byte[] clear) throws Exception { SecretKeySpec skeySpec=new SecretKeySpec(raw,"AES"); Cipher cipher=Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE,skeySpec); byte[] encrypted=cipher.doFinal(clear); return encrypted; }
Example 24
From project Sage-Mobile-Calc, under directory /src/org/connectbot/util/.
Source file: PubkeyUtils.java

public static byte[] cipher(int mode,byte[] data,byte[] secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { SecretKeySpec secretKeySpec=new SecretKeySpec(sha256(secret),"AES"); Cipher c=Cipher.getInstance("AES"); c.init(mode,secretKeySpec); return c.doFinal(data); }
Example 25
From project spring-security, under directory /crypto/src/main/java/org/springframework/security/crypto/encrypt/.
Source file: AesBytesEncryptor.java

public AesBytesEncryptor(String password,CharSequence salt,BytesKeyGenerator ivGenerator){ PBEKeySpec keySpec=new PBEKeySpec(password.toCharArray(),Hex.decode(salt),1024,256); SecretKey secretKey=newSecretKey("PBKDF2WithHmacSHA1",keySpec); this.secretKey=new SecretKeySpec(secretKey.getEncoded(),"AES"); encryptor=newCipher(AES_ALGORITHM); decryptor=newCipher(AES_ALGORITHM); this.ivGenerator=ivGenerator != null ? ivGenerator : NULL_IV_GENERATOR; }
Example 26
From project spring-social-facebook, under directory /spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/.
Source file: SignedRequestDecoder.java

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 27
From project springfaces, under directory /springfaces-mvc/src/main/java/org/springframework/springfaces/mvc/render/.
Source file: ClientFacesViewStateHandler.java

private Cipher getCipher(int mode,SecretKey secretKey,AlgorithmParameterSpec parameters) throws Exception { Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec secretKeySpec=new SecretKeySpec(secretKey.getEncoded(),"AES"); cipher.init(mode,secretKeySpec,parameters); return cipher; }
Example 28
From project teatrove, under directory /teaapps/src/main/java/org/teatrove/teaapps/contexts/.
Source file: CryptoContext.java

/** * Computes RFC 2104-compliant HMAC signature. * @param data The data to be signed. * @param key The signing key. * @return The Base64-encoded RFC 2104-compliant HMAC signature. * @throws java.security.SignatureException when signature generation fails */ public String calculateRFC2104HMAC(String data,String key) throws java.security.SignatureException { String result; try { SecretKeySpec signingKey=new SecretKeySpec(key.getBytes(),HMAC_SHA1_ALGORITHM); Mac mac=Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); byte[] rawHmac=mac.doFinal(data.getBytes()); result=new String(Base64.encodeBase64(rawHmac)); } catch ( Exception e) { throw new SignatureException("Failed to generate HMAC",e); } return result; }
Example 29
From project TextSecure, under directory /src/org/thoughtcrime/securesms/crypto/.
Source file: AsymmetricMasterCipher.java

private MasterCipher getMasterCipherForSecret(BigInteger secret){ byte[] secretBytes=secret.toByteArray(); SecretKeySpec cipherKey=deriveCipherKey(secretBytes); SecretKeySpec macKey=deriveMacKey(secretBytes); MasterSecret masterSecret=new MasterSecret(cipherKey,macKey); return new MasterCipher(masterSecret); }
Example 30
From project tinfoil-sms, under directory /branches/prephase1/src/com/tinfoil/sms/.
Source file: Encryption.java

public static String aes_encrypt(String password,String plaintext) throws Exception { byte[] secret_key=generateKey(password.getBytes()); byte[] clear=plaintext.getBytes(); SecretKeySpec secretKeySpec=new SecretKeySpec(secret_key,CIPHER_ALGORITHM); Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec); byte[] encrypted=cipher.doFinal(clear); String encryptedString=Base64.encodeToString(encrypted,Base64.DEFAULT); return encryptedString; }
Example 31
From project ajah, under directory /ajah-crypto/src/main/java/com/ajah/crypto/.
Source file: Crypto.java

/** * 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 32
From project aws-tvm-anonymous, under directory /src/com/amazonaws/tvm/.
Source file: Utilities.java

public static String sign(String content,String key){ try { byte[] data=content.getBytes(Constants.ENCODING_FORMAT); Mac mac=Mac.getInstance(Constants.SIGNATURE_METHOD); mac.init(new SecretKeySpec(key.getBytes(Constants.ENCODING_FORMAT),Constants.SIGNATURE_METHOD)); byte[] signature=Base64.encodeBase64(mac.doFinal(data)); return new String(signature,Constants.ENCODING_FORMAT); } catch ( Exception exception) { log.log(Level.SEVERE,"Exception during sign",exception); } return null; }
Example 33
From project aws-tvm-identity, under directory /src/com/amazonaws/tvm/.
Source file: Utilities.java

public static String sign(String content,String key){ try { byte[] data=content.getBytes(Constants.ENCODING_FORMAT); Mac mac=Mac.getInstance(Constants.SIGNATURE_METHOD); mac.init(new SecretKeySpec(key.getBytes(Constants.ENCODING_FORMAT),Constants.SIGNATURE_METHOD)); char[] signature=Hex.encodeHex(mac.doFinal(data)); return new String(signature); } catch ( Exception exception) { log.log(Level.SEVERE,"Exception during sign",exception); } return null; }
Example 34
From project candlepin, under directory /src/main/java/org/candlepin/config/.
Source file: EncryptedValueConfigurationParser.java

public String decryptValue(String toDecrypt,String passphrase){ log.info("decrypt called"); if (!toDecrypt.startsWith("$1$")) { log.debug("this is not an encrypted string"); return toDecrypt; } toDecrypt=toDecrypt.substring(3); try { Cipher cipher; cipher=Cipher.getInstance("AES/CBC/PKCS5Padding"); String ivString=passphrase + passphrase; String iv=DigestUtils.sha256Hex(ivString); String passphraseDigest=DigestUtils.sha256Hex(passphrase); SecretKeySpec spec=new SecretKeySpec(Arrays.copyOfRange(passphraseDigest.getBytes(),0,32),"AES"); cipher.init(Cipher.DECRYPT_MODE,spec,new IvParameterSpec(iv.getBytes(),0,16)); log.info("gh10"); byte[] b64bytes=Base64.decodeBase64(toDecrypt); String plaintext=new String(cipher.doFinal(b64bytes)); return plaintext; } catch ( Exception e) { log.info("Failure trying to decrypt" + toDecrypt,e); throw new RuntimeException(e); } }
Example 35
From project cas, under directory /cas-server-extension-clearpass/src/main/java/org/jasig/cas/extension/clearpass/.
Source file: EncryptedMapDecorator.java

private static Key getSecretKey(String secretKeyAlgorithm,String secretKey,String salt) throws Exception { SecretKeyFactory factory=SecretKeyFactory.getInstance(SECRET_KEY_FACTORY_ALGORITHM); KeySpec spec=new PBEKeySpec(secretKey.toCharArray(),char2byte(salt),65536,128); SecretKey tmp=factory.generateSecret(spec); SecretKey secret=new SecretKeySpec(tmp.getEncoded(),secretKeyAlgorithm); return secret; }
Example 36
From project cogroo4, under directory /lang/pt_br/cogroo-addon/src/org/cogroo/addon/util/.
Source file: SecurityUtil.java

private byte[] encrypt(byte[] secretKey,String data) throws InvalidKeyException { byte[] encryptedData=null; try { Cipher aescf=Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec ivspec=new IvParameterSpec(new byte[16]); aescf.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(secretKey,"AES"),ivspec); encryptedData=aescf.doFinal(data.getBytes(UTF8)); } catch ( Exception e) { LOG.log(Level.SEVERE,"Exception encrypting data",e); } return encryptedData; }
Example 37
From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.
Source file: IdentityApplic.java

public static SecretKey keyExchange(ObjectInputStream in,ObjectOutputStream out) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IOException, ClassNotFoundException, NoSuchPaddingException { KeyPairGenerator gen=KeyPairGenerator.getInstance("RSA"); gen.initialize(1024,new SecureRandom()); KeyPair keys=gen.generateKeyPair(); PublicKey publicKey=keys.getPublic(); PrivateKey privateKey=keys.getPrivate(); out.writeObject(new KeyExchangeClient(publicKey)); out.flush(); KeyExchangeServer response=(KeyExchangeServer)in.readObject(); Cipher decryptor=Cipher.getInstance("RSA/ECB/PKCS1Padding"); decryptor.init(Cipher.DECRYPT_MODE,privateKey); byte[] sessionKeyEncoded=decryptor.doFinal(response.getCryptedSessionKey()); return new SecretKeySpec(sessionKeyEncoded,"DES"); }
Example 38
From project cp-common-utils, under directory /src/com/clarkparsia/common/io/.
Source file: EncryptedFile.java

/** * Given a string key, either trim it down so its an appropriate size, or pad it to make it long enough * @param theKey the key use * @return a secret key based on the provided key string. */ private static SecretKey makeGoodKey(String theKey){ String aKey=theKey; if (aKey.length() > 8) { aKey=aKey.substring(0,8); } else if (aKey.length() < 8) { while (aKey.length() < 8) { aKey+="0"; } } return new SecretKeySpec(aKey.getBytes(),"DES"); }
Example 39
From project crest, under directory /core/src/main/java/org/codegist/crest/security/oauth/v1/.
Source file: OAuthsV1.java

private static String sign(OAuthToken consumerOAuthToken,OAuthToken accessOAuthToken,MethodType methodType,String url,List<EncodedPair> oauthParams) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { List<EncodedPair> sorted=sortByNameAndValues(oauthParams); String signUri=constructRequestURL(url); String signParams=join(sorted,'&','=',false,false); String signature=consumerOAuthToken.getSecret() + "&" + accessOAuthToken.getSecret(); Mac mac=Mac.getInstance(SIGN_METH_4_J); mac.init(new SecretKeySpec(signature.getBytes(ENC),SIGN_METH_4_J)); String data=methodType.name() + "&" + encode(signUri,ENC)+ "&"+ encode(signParams,ENC); String encoded=new String(Base64.encodeToByte(mac.doFinal(data.getBytes(ENC))),ENC); LOGGER.debug("Signature[data=\"%s\",signature=\"%s\",result=\"%s\"]",data,signature,encoded); return encoded; }
Example 40
From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/location/.
Source file: AESKeyGenerator.java

/** * The only public function and is *the* function of this class. It generates the k_1, k_2, etc. from parameters Friend, f, and time or whatever it is you want to "encrypt", toEncrypt. */ public byte[] generate_k(String dhkey,String toEncrypt){ byte[] retVal; try { mCipher=Cipher.getInstance("AES"); MessageDigest hasher=MessageDigest.getInstance("SHA-256"); byte[] key256=hasher.digest(dhkey.getBytes()); SecretKeySpec K=new SecretKeySpec(key256,"AES"); mCipher.init(Cipher.ENCRYPT_MODE,K); try { retVal=mCipher.doFinal(toEncrypt.getBytes()); return retVal; } catch ( Exception e) { } } catch ( Exception e) { } return null; }
Example 41
From project figgo, under directory /src/main/java/br/octahedron/figgo/modules/admin/util/.
Source file: Route53Util.java

protected static String sign(String content,String key) throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IllegalStateException { Mac mac=Mac.getInstance(MAC_ALGORITHM); SecretKey skey=new SecretKeySpec(key.getBytes(),KEY_ALGORITHM); mac.init(skey); mac.update(content.getBytes()); return new String(Base64.encodeBase64((mac.doFinal()))); }
Example 42
public static byte[] sha256(final byte[] message,final byte[] key){ final Mac mac; try { mac=Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key,"HmacSHA256")); } catch ( Exception e) { throw new RuntimeException(e); } return mac.doFinal(message); }
Example 43
/** * 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 44
From project Gibberbot, under directory /src/net/java/otr4j/crypto/.
Source file: OtrCryptoEngineImpl.java

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 45
From project hdiv, under directory /hdiv-core/src/main/java/org/hdiv/cipher/.
Source file: KeyFactory.java

/** * This method is called whenever a key needs to be generated. * @return Key the encryption key */ public Key generateKey(){ try { SecureRandom random=SecureRandom.getInstance(this.prngAlgorithm,this.provider); byte[] iv=new byte[16]; random.nextBytes(iv); KeyGenerator kgen=KeyGenerator.getInstance(algorithm); kgen.init(keySize,random); SecretKey skey=kgen.generateKey(); byte[] raw=skey.getEncoded(); SecretKeySpec skeySpec=new SecretKeySpec(raw,algorithm); Key key=new Key(); key.setKey(skeySpec); key.setInitVector(iv); return key; } catch ( Exception e) { String errorMessage=HDIVUtil.getMessage("key.factory.generate",e.getMessage()); throw new HDIVException(errorMessage,e); } }
Example 46
From project http-testing-harness, under directory /server-provider/src/main/java/org/sonatype/tests/http/server/jetty/behaviour/.
Source file: NTLMAuth.java

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 47
From project JavaJunction, under directory /src/main/java/edu/stanford/junction/extra/.
Source file: Encryption.java

private void init(){ try { mCipher=Cipher.getInstance("AES/CBC/PKCS5PADDING"); mKeySpec=new SecretKeySpec(mKey,"AES"); } catch ( Exception e) { e.printStackTrace(); } }
Example 48
From project jftp, under directory /src/main/java/com/myjavaworld/jftp/.
Source file: FavoritesManager.java

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 49
From project jPOS, under directory /jpos/src/test/java/org/jpos/security/jceadapter/.
Source file: JCEHandlerTest.java

@Test public void testEncryptDESKeyThrowsNullPointerException() throws Throwable { byte[] bytes=new byte[1]; Key encryptingKey=new SecretKeySpec(bytes,"testJCEHandlerParam2"); try { new JCEHandler((Provider)null).encryptDESKey((short)100,null,encryptingKey); fail("Expected NullPointerException to be thrown"); } catch ( NullPointerException ex) { assertNull("ex.getMessage()",ex.getMessage()); assertEquals("(SecretKeySpec) encryptingKey.getAlgorithm()","testJCEHandlerParam2",((SecretKeySpec)encryptingKey).getAlgorithm()); } }
Example 50
From project jsecurity, under directory /core/src/main/java/org/apache/ki/crypto/.
Source file: BlowfishCipher.java

/** * Calls the {@link #init(javax.crypto.Cipher,int,java.security.Key)} and then{@link #crypt(javax.crypto.Cipher,byte[])}. Ensures that the key is never null by using the {@link #getKey() default key} if the method argument key is <code>null</code>. * @param bytes the bytes to crypt * @param mode the JDK Cipher mode * @param key the key to use to do the cryption. If <code>null</code> the {@link #getKey() default key} will be used. * @return the resulting crypted byte array */ protected byte[] crypt(byte[] bytes,int mode,byte[] key){ javax.crypto.Cipher cipher=newCipherInstance(); java.security.Key jdkKey; if (key == null) { jdkKey=getKey(); } else { jdkKey=new SecretKeySpec(key,ALGORITHM); } init(cipher,mode,jdkKey); return crypt(cipher,bytes); }
Example 51
From project Karotz-Plugin, under directory /src/main/java/org/jenkinsci/plugins/karotz/.
Source file: KarotzUtil.java

/** * 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 52
From project keepassdroid, under directory /src/com/keepassdroid/crypto/.
Source file: CipherFactory.java

/** * Generate appropriate cipher based on KeePass 2.x UUID's * @param uuid * @return * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException * @throws InvalidKeyException */ public static Cipher getInstance(UUID uuid,byte[] key,byte[] IV) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { if (uuid.equals(AES_CIPHER)) { Cipher cipher=CipherFactory.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(key,"AES"),new IvParameterSpec(IV)); return cipher; } throw new NoSuchAlgorithmException("UUID unrecognized."); }
Example 53
From project nevernote, under directory /src/cx/fbn/nevernote/evernote/.
Source file: EnCrypt.java

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 54
From project NFCShopping, under directory /mobile phone client/NFCShopping/src/weibo4android/http/.
Source file: OAuth.java

/** * 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 55
From project obpro_team_p, under directory /twitter/twitter4j-core/src/main/java/twitter4j/auth/.
Source file: OAuthAuthorization.java

/** * 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 56
From project penrose-server, under directory /common/src/java/org/safehaus/penrose/samba/.
Source file: SambaUtil.java

public static String encryptLMPassword(String password) throws Exception { if (password == null) return null; byte[] bytes=password.toUpperCase().getBytes("UTF-8"); if (bytes.length != 14) { byte[] b=new byte[14]; for (int i=0; i < bytes.length && i < 14; i++) b[i]=bytes[i]; bytes=b; } byte[] key1=convert(bytes,0); byte[] key2=convert(bytes,7); byte[] magic=new BigInteger("4B47532140232425",16).toByteArray(); SecretKeySpec spec1=new SecretKeySpec(key1,"DES"); Cipher cipher1=Cipher.getInstance("DES"); cipher1.init(Cipher.ENCRYPT_MODE,spec1); byte[] result1=cipher1.doFinal(magic); SecretKeySpec spec2=new SecretKeySpec(key2,"DES"); Cipher cipher2=Cipher.getInstance("DES"); cipher2.init(Cipher.ENCRYPT_MODE,spec2); byte[] result2=cipher2.doFinal(magic); System.arraycopy(result2,0,result1,8,8); return BinaryUtil.encode(BinaryUtil.BIG_INTEGER,result1).toUpperCase(); }
Example 57
From project Red5, under directory /src/org/red5/server/net/rtmp/.
Source file: RTMPHandshake.java

/** * 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 58
From project red5-mavenized, under directory /red5_base/src/main/java/org/red5/server/net/rtmp/.
Source file: RTMPHandshake.java

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 59
From project red5-server, under directory /src/org/red5/server/net/rtmp/.
Source file: RTMPHandshake.java

/** * 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 60
From project RS-MVC, under directory /core/src/main/java/cx/ath/mancel01/restmvc/.
Source file: Session.java

public static String sign(String message){ byte[] key=privatekey.getBytes(); if (key.length == 0) { return message; } try { Mac mac=Mac.getInstance("HmacSHA1"); SecretKeySpec signingKey=new SecretKeySpec(key,"HmacSHA1"); mac.init(signingKey); byte[] messageBytes=message.getBytes("utf-8"); byte[] result=mac.doFinal(messageBytes); int len=result.length; char[] hexChars=new char[len * 2]; for (int charIndex=0, startIndex=0; charIndex < hexChars.length; ) { int bite=result[startIndex++] & 0xff; hexChars[charIndex++]=HEX_CHARS[bite >> 4]; hexChars[charIndex++]=HEX_CHARS[bite & 0xf]; } return new String(hexChars); } catch ( Exception ex) { throw new RuntimeException(ex); } }
Example 61
From project sandbox, under directory /authenticators/xwiki-authentication-ntlm/src/main/java/com/xwiki/authentication/ntlm/.
Source file: NTLMAuthServiceImpl.java

protected String encryptText(String text,XWikiContext context){ try { String secretKey=null; secretKey=context.getWiki().Param("xwiki.authentication.encryptionKey"); secretKey=secretKey.substring(0,24); if (secretKey != null) { SecretKeySpec key=new SecretKeySpec(secretKey.getBytes(),"TripleDES"); Cipher cipher=Cipher.getInstance("TripleDES"); cipher.init(Cipher.ENCRYPT_MODE,key); byte[] encrypted=cipher.doFinal(text.getBytes()); String encoded=Base64.encode(encrypted); return encoded.replaceAll("=","_"); } else { LOG.error("Encryption key not defined"); } } catch ( Exception e) { LOG.error("Failed to encrypt text",e); } return null; }
Example 62
From project sauce-ondemand-plugin, under directory /src/main/java/hudson/plugins/sauce_ondemand/.
Source file: SauceOnDemandReport.java

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 63
From project security, under directory /impl/src/main/java/org/jboss/seam/security/crypto/.
Source file: MacBasedPRF.java

public void init(byte[] P){ try { mac.init(new SecretKeySpec(P,macAlgorithm)); } catch ( InvalidKeyException e) { throw new RuntimeException(e); } }
Example 64
From project shiro, under directory /core/src/main/java/org/apache/shiro/crypto/.
Source file: JcaCipherService.java

private javax.crypto.Cipher initNewCipher(int jcaCipherMode,byte[] key,byte[] iv,boolean streaming) throws CryptoException { javax.crypto.Cipher cipher=newCipherInstance(streaming); java.security.Key jdkKey=new SecretKeySpec(key,getAlgorithmName()); IvParameterSpec ivSpec=null; if (iv != null && iv.length > 0) { ivSpec=new IvParameterSpec(iv); } init(cipher,jcaCipherMode,jdkKey,ivSpec,getSecureRandom()); return cipher; }
Example 65
From project sms-backup-plus, under directory /src/com/zegoggles/smssync/.
Source file: XOAuthConsumer.java

private String generateSig(HttpRequest request,HttpParameters requestParameters) throws Exception { String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes=keyString.getBytes(OAuth.ENCODING); SecretKey key=new SecretKeySpec(keyBytes,MAC_NAME); Mac mac=Mac.getInstance(MAC_NAME); mac.init(key); String sbs=new SignatureBaseString(request,requestParameters).generate(); return base64(mac.doFinal(sbs.getBytes(OAuth.ENCODING))); }
Example 66
From project sparsemapcontent, under directory /core/src/main/java/org/sakaiproject/nakamura/lite/accesscontrol/.
Source file: PrincipalTokenValidator.java

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 67
From project spring-android, under directory /spring-android-auth/src/main/java/org/springframework/security/crypto/encrypt/.
Source file: AndroidAesBytesEncryptor.java

public AndroidAesBytesEncryptor(String password,CharSequence salt,BytesKeyGenerator ivGenerator){ PBEKeySpec keySpec=new PBEKeySpec(password.toCharArray(),Hex.decode(salt),1024,256); SecretKey secretKey=newSecretKey("PBEWITHSHA256AND256BITAES-CBC-BC",keySpec); this.secretKey=new SecretKeySpec(secretKey.getEncoded(),"AES"); encryptor=newCipher(AES_ALGORITHM); decryptor=newCipher(AES_ALGORITHM); this.ivGenerator=ivGenerator; }
Example 68
From project spring-crypto-utils, under directory /src/main/java/com/springcryptoutils/core/cipher/symmetric/.
Source file: Base64EncodedCiphererImpl.java

/** * Encrypts or decrypts a message. The encryption/decryption mode depends on the configuration of the mode parameter. * @param key a base64 encoded version of the symmetric key * @param initializationVector a base64 encoded version of theinitialization vector * @param message if in encryption mode, the clear-text message to encrypt,otherwise a base64 encoded version of the message to decrypt * @return if in encryption mode, returns a base64 encoded version of theencrypted message, otherwise returns the decrypted clear-text message * @throws SymmetricEncryptionException on runtime errors * @see #setMode(com.google.code.springcryptoutils.core.cipher.Mode) */ public String encrypt(String key,String initializationVector,String message){ try { IvParameterSpec initializationVectorSpec=new IvParameterSpec(Base64.decodeBase64(initializationVector)); final SecretKeySpec keySpec=new SecretKeySpec(Base64.decodeBase64(key),keyAlgorithm); final Cipher cipher=(((provider == null) || (provider.length() == 0)) ? Cipher.getInstance(cipherAlgorithm) : Cipher.getInstance(cipherAlgorithm,provider)); byte[] messageAsByteArray; switch (mode) { case ENCRYPT: cipher.init(Cipher.ENCRYPT_MODE,keySpec,initializationVectorSpec); messageAsByteArray=message.getBytes(charsetName); final byte[] encryptedMessage=cipher.doFinal(messageAsByteArray); return new String(Base64.encodeBase64(encryptedMessage,chunkOutput)); case DECRYPT: cipher.init(Cipher.DECRYPT_MODE,keySpec,initializationVectorSpec); messageAsByteArray=Base64.decodeBase64(message); final byte[] decryptedMessage=cipher.doFinal(messageAsByteArray); return new String(decryptedMessage,charsetName); default : return null; } } catch (Exception e) { throw new SymmetricEncryptionException("error encrypting/decrypting message; mode=" + mode,e); } }
Example 69
From project spring-social, under directory /spring-social-core/src/main/java/org/springframework/social/oauth1/.
Source file: SigningSupport.java

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 70
From project springside, under directory /modules/core/src/main/java/org/springside/modules/security/utils/.
Source file: Cryptos.java

/** * ???HMAC-SHA1?????????, ?????????,????20???. * @param input ???????????? * @param key HMAC-SHA1??? */ public static byte[] hmacSha1(byte[] input,byte[] key){ try { SecretKey secretKey=new SecretKeySpec(key,HMACSHA1); Mac mac=Mac.getInstance(HMACSHA1); mac.init(secretKey); return mac.doFinal(input); } catch ( GeneralSecurityException e) { throw Exceptions.unchecked(e); } }
Example 71
From project springside4, under directory /modules/core/src/main/java/org/springside/modules/security/utils/.
Source file: Cryptos.java

/** * ???HMAC-SHA1?????????, ?????????,????20???. * @param input ???????????? * @param key HMAC-SHA1??? */ public static byte[] hmacSha1(byte[] input,byte[] key){ try { SecretKey secretKey=new SecretKeySpec(key,HMACSHA1); Mac mac=Mac.getInstance(HMACSHA1); mac.init(secretKey); return mac.doFinal(input); } catch ( GeneralSecurityException e) { throw Exceptions.unchecked(e); } }
Example 72
From project sshj, under directory /src/main/java/net/schmizz/sshj/transport/cipher/.
Source file: BaseCipher.java

@Override public void init(Mode mode,byte[] key,byte[] iv){ key=BaseCipher.resize(key,bsize); iv=BaseCipher.resize(iv,ivsize); try { cipher=SecurityUtils.getCipher(transformation); cipher.init((mode == Mode.Encrypt ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE),new SecretKeySpec(key,algorithm),new IvParameterSpec(iv)); } catch ( GeneralSecurityException e) { cipher=null; throw new SSHRuntimeException(e); } }
Example 73
From project stackmob-java-client-sdk, under directory /src/main/java/com/stackmob/sdk/api/.
Source file: StackMobSession.java

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 74
From project syslog4j, under directory /src/main/java/com/nesscomputing/syslog4j/impl/message/modifier/mac/.
Source file: MacSyslogMessageModifierConfig.java

public MacSyslogMessageModifierConfig(String macAlgorithm,String keyAlgorithm,byte[] keyBytes){ this.macAlgorithm=macAlgorithm; this.keyAlgorithm=keyAlgorithm; try { this.key=new SecretKeySpec(keyBytes,keyAlgorithm); } catch ( IllegalArgumentException iae) { throw new SyslogRuntimeException(iae); } }
Example 75
From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/auth/.
Source file: NTLMEngineImpl.java

/** * Creates a DES encryption key from the given key material. * @param bytes A byte array containing the DES key material. * @param offset The offset in the given byte array at which the 7-byte key material starts. * @return A DES encryption key created from the key material starting atthe specified offset in the given byte array. */ private static Key createDESKey(byte[] bytes,int offset){ byte[] keyBytes=new byte[7]; System.arraycopy(bytes,offset,keyBytes,0,7); byte[] material=new byte[8]; material[0]=keyBytes[0]; material[1]=(byte)(keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1); material[2]=(byte)(keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2); material[3]=(byte)(keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3); material[4]=(byte)(keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4); material[5]=(byte)(keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5); material[6]=(byte)(keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6); material[7]=(byte)(keyBytes[6] << 1); oddParity(material); return new SecretKeySpec(material,"DES"); }
Example 76
From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/oauth/signpost/signature/.
Source file: HmacSha1MessageSigner.java

@Override public String sign(HttpRequest request,HttpParameters requestParams) throws OAuthMessageSignerException { try { String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes=keyString.getBytes(OAuth.ENCODING); SecretKey key=new SecretKeySpec(keyBytes,MAC_NAME); Mac mac=Mac.getInstance(MAC_NAME); mac.init(key); String sbs=new SignatureBaseString(request,requestParams).generate(); OAuth.debugOut("SBS",sbs); byte[] text=sbs.getBytes(OAuth.ENCODING); return base64Encode(mac.doFinal(text)).trim(); } catch ( GeneralSecurityException e) { throw new OAuthMessageSignerException(e); } catch ( UnsupportedEncodingException e) { throw new OAuthMessageSignerException(e); } }
Example 77
From project AndroidBillingLibrary, under directory /AndroidBillingLibrary/src/net/robotmedia/billing/utils/.
Source file: AESObfuscator.java

public AESObfuscator(byte[] salt,String password){ try { SecretKeyFactory factory=SecretKeyFactory.getInstance(KEYGEN_ALGORITHM); KeySpec keySpec=new PBEKeySpec(password.toCharArray(),salt,1024,256); SecretKey tmp=factory.generateSecret(keySpec); SecretKey secret=new SecretKeySpec(tmp.getEncoded(),"AES"); mEncryptor=Cipher.getInstance(CIPHER_ALGORITHM); mEncryptor.init(Cipher.ENCRYPT_MODE,secret,new IvParameterSpec(IV)); mDecryptor=Cipher.getInstance(CIPHER_ALGORITHM); mDecryptor.init(Cipher.DECRYPT_MODE,secret,new IvParameterSpec(IV)); } catch ( GeneralSecurityException e) { throw new RuntimeException("Invalid environment",e); } }
Example 78
From project android_external_oauth, under directory /core/src/main/java/net/oauth/signature/.
Source file: HMAC_SHA1.java

private byte[] computeSignature(String baseString) throws GeneralSecurityException, UnsupportedEncodingException { SecretKey key=null; synchronized (this) { if (this.key == null) { String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes=keyString.getBytes(ENCODING); this.key=new SecretKeySpec(keyBytes,MAC_NAME); } key=this.key; } Mac mac=Mac.getInstance(MAC_NAME); mac.init(key); byte[] text=baseString.getBytes(ENCODING); return mac.doFinal(text); }
Example 79
From project Android_Pusher, under directory /src/com/emorym/android_pusher/.
Source file: Pusher.java

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 80
From project BazaarUtils, under directory /src/com/android/vending/licensing/.
Source file: AESObfuscator.java

/** * @param salt an array of random bytes to use for each (un)obfuscation * @param applicationId application identifier, e.g. the package name * @param deviceId device identifier. Use as many sources as possible tocreate this unique identifier. */ public AESObfuscator(byte[] salt,String applicationId,String deviceId){ try { SecretKeyFactory factory=SecretKeyFactory.getInstance(KEYGEN_ALGORITHM); KeySpec keySpec=new PBEKeySpec((applicationId + deviceId).toCharArray(),salt,1024,256); SecretKey tmp=factory.generateSecret(keySpec); SecretKey secret=new SecretKeySpec(tmp.getEncoded(),"AES"); mEncryptor=Cipher.getInstance(CIPHER_ALGORITHM); mEncryptor.init(Cipher.ENCRYPT_MODE,secret,new IvParameterSpec(IV)); mDecryptor=Cipher.getInstance(CIPHER_ALGORITHM); mDecryptor.init(Cipher.DECRYPT_MODE,secret,new IvParameterSpec(IV)); } catch ( GeneralSecurityException e) { throw new RuntimeException("Invalid environment",e); } }
Example 81
From project caseconductor-platform, under directory /utest-common/src/main/java/com/utest/util/.
Source file: CrytographicTool.java

/** * Encrypts a text. * @param source the plain text to encrypt. * @return the encrypted text. * @throws Exception */ public static String encrypt(final String source,final CryptoAlgorithm algorithm,final String blowfishKey) throws Exception { String result=""; if (CryptoAlgorithm.BLOWFISH.equals(algorithm)) { final byte[] keyBytes=new BigInteger(blowfishKey,16).toByteArray(); final Key key=new SecretKeySpec(keyBytes,"Blowfish"); final BASE64Encoder encoder=new BASE64Encoder(); final Cipher cipher=Cipher.getInstance("Blowfish/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE,key); final byte[] ciphertext=cipher.doFinal(source.getBytes("UTF8")); result=encoder.encode(ciphertext); return result; } if (CryptoAlgorithm.DES.equals(algorithm)) { result=DES.encrypt(source); } return result; }
Example 82
From project chililog-server, under directory /src/main/java/org/chililog/server/common/.
Source file: CryptoUtils.java

/** * <p> Encrypt a plain text string using AES. The output is an encrypted plain text string. See http://stackoverflow.com/questions/992019/java-256bit-aes-encryption/992413#992413 </p> <p> The algorithm used is <code>base64(aes(plainText))</code> </p> * @param plainText text to encrypt * @param password password to use for encryption * @return encrypted text * @throws ChiliLogException */ public static String encryptAES(String plainText,String password) throws ChiliLogException { try { SecretKeyFactory factory=SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec=new PBEKeySpec(password.toCharArray(),AES_ENCRYPTION_STRING_SALT,1024,128); SecretKey tmp=factory.generateSecret(spec); SecretKey secret=new SecretKeySpec(tmp.getEncoded(),"AES"); byte[] plainTextBytes=plainText.getBytes("UTF-8"); AlgorithmParameterSpec paramSpec=new IvParameterSpec(AES_ENCRYPTION_INTIALIZATION_VECTOR); Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE,secret,paramSpec); byte[] cipherText=cipher.doFinal(plainTextBytes); Base64 encoder=new Base64(1000,new byte[]{},false); return encoder.encodeToString(cipherText); } catch ( Exception ex) { throw new ChiliLogException(ex,"Error attempting to encrypt. " + ex.getMessage()); } }
Example 83
From project dnieprov, under directory /src/org/dnieprov/driver/.
Source file: DnieSecureChannel.java

private byte[] cipher(byte data[],boolean encrypt) throws NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchPaddingException { int dir=encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE; byte[] keyTdesBytes=new byte[24]; System.arraycopy(kenc,0,keyTdesBytes,0,16); System.arraycopy(kenc,0,keyTdesBytes,16,8); byte[] ivBytes=new byte[8]; for (int i=0; i < 8; i++) { ivBytes[i]=0x00; } SecretKey keyTdes=new SecretKeySpec(keyTdesBytes,"DESede"); Cipher des=Cipher.getInstance("DESede/CBC/NoPadding"); IvParameterSpec iv=new IvParameterSpec(ivBytes); des.init(dir,keyTdes,iv); return des.doFinal(data); }
Example 84
private byte[] computeSignature(String baseString) throws GeneralSecurityException, UnsupportedEncodingException { SecretKey key=null; synchronized (this) { if (this.key == null) { String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes=keyString.getBytes(ENCODING); this.key=new SecretKeySpec(keyBytes,MAC_NAME); } key=this.key; } Mac mac=Mac.getInstance(MAC_NAME); mac.init(key); byte[] text=baseString.getBytes(ENCODING); return mac.doFinal(text); }
Example 85
From project GradeCalculator-Android, under directory /GradeCalculator/src/com/jetheis/android/grades/billing/.
Source file: Security.java

private static String encryptUnlockKey(Context context,byte[] salt){ Cipher encrypter; try { SecretKeyFactory factory=SecretKeyFactory.getInstance(KEYGEN_ALGORITHM); KeySpec keySpec=new PBEKeySpec(getPasswordForDevice(context),salt,1024,256); SecretKey tmp=factory.generateSecret(keySpec); SecretKey secret=new SecretKeySpec(tmp.getEncoded(),"AES"); encrypter=Cipher.getInstance(CIPHER_ALGORITHM); encrypter.init(Cipher.ENCRYPT_MODE,secret,new IvParameterSpec(AES_IV)); } catch ( GeneralSecurityException e) { throw new RuntimeException("Invalid environment",e); } try { return Base64.encodeToString(salt,Base64.NO_WRAP) + Base64.encodeToString(encrypter.doFinal(getUnlockKeyForDevice(context).getBytes("UTF-8")),Base64.NO_WRAP); } catch ( IllegalBlockSizeException e) { throw new RuntimeException("Encoding error",e); } catch ( BadPaddingException e) { throw new RuntimeException("Encoding error",e); } catch ( UnsupportedEncodingException e) { throw new RuntimeException("Invalid environment",e); } }
Example 86
From project httpClient, under directory /httpclient/src/main/java/org/apache/http/impl/auth/.
Source file: NTLMEngineImpl.java

/** * Creates a DES encryption key from the given key material. * @param bytes A byte array containing the DES key material. * @param offset The offset in the given byte array at which the 7-byte key material starts. * @return A DES encryption key created from the key material starting atthe specified offset in the given byte array. */ private static Key createDESKey(byte[] bytes,int offset){ byte[] keyBytes=new byte[7]; System.arraycopy(bytes,offset,keyBytes,0,7); byte[] material=new byte[8]; material[0]=keyBytes[0]; material[1]=(byte)(keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1); material[2]=(byte)(keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2); material[3]=(byte)(keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3); material[4]=(byte)(keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4); material[5]=(byte)(keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5); material[6]=(byte)(keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6); material[7]=(byte)(keyBytes[6] << 1); oddParity(material); return new SecretKeySpec(material,"DES"); }
Example 87
From project isohealth, under directory /Oauth/java/core/commons/src/main/java/net/oauth/signature/.
Source file: HMAC_SHA1.java

private byte[] computeSignature(String baseString) throws GeneralSecurityException, UnsupportedEncodingException { SecretKey key=null; synchronized (this) { if (this.key == null) { String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes=keyString.getBytes(ENCODING); this.key=new SecretKeySpec(keyBytes,MAC_NAME); } key=this.key; } Mac mac=Mac.getInstance(MAC_NAME); mac.init(key); byte[] text=baseString.getBytes(ENCODING); return mac.doFinal(text); }
Example 88
public RaopServer(RaopSession session){ super("RaopServer " + session.getId()); this.port=session.getControlPort() - 1; this.session=session; try { this.aesCipher=Cipher.getInstance("AES/CBC/NOPADDING"); receiveSocket=new DatagramSocket(port); DataLine.Info info=new DataLine.Info(SourceDataLine.class,new AudioFormat(session.getFormat().getSampleRate(),session.getFormat().getSampleSize(),2,true,true)); line=(SourceDataLine)AudioSystem.getLine(info); line.open(); line.start(); } catch ( Exception e) { throw new RuntimeException(e); } secretKey=new SecretKeySpec(session.getAesKey(),"AES"); secretKey=new SecretKeySpec(session.getAesKey(),"AES"); keySpec=new IvParameterSpec(session.getAesIv()); int frameSize=session.getFormat().getFrameSize(); alac=AlacDecodeUtils.create_alac(session.getFormat().getSampleSize(),2); alac.setSetinfo_max_samples_per_frame(frameSize); alac.setSetinfo_rice_historymult(session.getFormat().getRiceHistoryMult()); alac.setSetinfo_rice_initialhistory(session.getFormat().getRiceInitialHistory()); alac.setSetinfo_rice_kmodifier(session.getFormat().getRiceKModifier()); alac.setSetinfo_sample_size(session.getFormat().getSampleSize()); outbuffer=new int[frameSize * 4]; outbufferBytes=new byte[outbuffer.length * 2]; }
Example 89
From project java_binding_v1, under directory /src/com/tripit/auth/.
Source file: OAuthCredential.java

private String generateSignature(String baseUrl,SortedMap<String,String> args) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { String encoding="UTF-8"; baseUrl=URLEncoder.encode(baseUrl,encoding); StringBuilder sb=new StringBuilder(); boolean isFirst=true; for ( Map.Entry<String,String> arg : args.entrySet()) { if (isFirst) { isFirst=false; } else { sb.append('&'); } sb.append(URLEncoder.encode(arg.getKey(),encoding)); sb.append('='); sb.append(URLEncoder.encode(arg.getValue(),encoding)); } String parameters=URLEncoder.encode(sb.toString(),encoding); String signatureBaseString="GET&" + baseUrl + "&"+ parameters; String key=(consumerSecret != null ? consumerSecret : "") + "&" + (userSecret != null ? userSecret : ""); String macName="HmacSHA1"; Mac mac=Mac.getInstance(macName); mac.init(new SecretKeySpec(key.getBytes(encoding),macName)); byte[] signature=mac.doFinal(signatureBaseString.getBytes(encoding)); return new Base64().encodeToString(signature).trim(); }
Example 90
From project jboss-sasl, under directory /src/main/java/org/jboss/sasl/digest/.
Source file: DigestMD5Base.java

/** * 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 91
From project JGit, under directory /org.spearce.jgit/src/org/spearce/jgit/transport/.
Source file: AmazonS3.java

/** * Create a new S3 client for the supplied user information. <p> The connection properties are a subset of those supported by the popular <a href="http://jets3t.s3.amazonaws.com/index.html">jets3t</a> library. For example: <pre> # AWS Access and Secret Keys (required) accesskey: <YourAWSAccessKey> secretkey: <YourAWSSecretKey> # Access Control List setting to apply to uploads, must be one of: # PRIVATE, PUBLIC_READ (defaults to PRIVATE). acl: PRIVATE # Number of times to retry after internal error from S3. httpclient.retry-max: 3 # End-to-end encryption (hides content from S3 owners) password: <encryption pass-phrase> crypto.algorithm: PBEWithMD5AndDES </pre> * @param props connection properties. */ public AmazonS3(final Properties props){ publicKey=props.getProperty("accesskey"); if (publicKey == null) throw new IllegalArgumentException("Missing accesskey."); final String secret=props.getProperty("secretkey"); if (secret == null) throw new IllegalArgumentException("Missing secretkey."); privateKey=new SecretKeySpec(Constants.encodeASCII(secret),HMAC); final String pacl=props.getProperty("acl","PRIVATE"); if ("PRIVATE".equalsIgnoreCase(pacl)) acl="private"; else if ("PUBLIC".equalsIgnoreCase(pacl)) acl="public-read"; else if ("PUBLIC-READ".equalsIgnoreCase(pacl)) acl="public-read"; else if ("PUBLIC_READ".equalsIgnoreCase(pacl)) acl="public-read"; else throw new IllegalArgumentException("Invalid acl: " + pacl); try { final String cPas=props.getProperty("password"); if (cPas != null) { String cAlg=props.getProperty("crypto.algorithm"); if (cAlg == null) cAlg="PBEWithMD5AndDES"; encryption=new WalkEncryption.ObjectEncryptionV2(cAlg,cPas); } else { encryption=WalkEncryption.NONE; } } catch ( InvalidKeySpecException e) { throw new IllegalArgumentException("Invalid encryption",e); } catch ( NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid encryption",e); } maxAttempts=Integer.parseInt(props.getProperty("httpclient.retry-max","3")); proxySelector=ProxySelector.getDefault(); }
Example 92
From project jmeter-components, under directory /src/main/java/com/atlantbh/jmeter/plugins/oauth/.
Source file: OAuthGenerator.java

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 93
public JreepadTreeModel read(InputStream in) throws IOException { while (in.read() != '\n') ; Cipher cipher=null; try { cipher=Cipher.getInstance(EncryptedWriter.ALGORITHM); Key key=new SecretKeySpec(password.getBytes(),EncryptedWriter.ALGORITHM); cipher.init(Cipher.DECRYPT_MODE,key); } catch ( GeneralSecurityException e) { throw new IOException(e.toString()); } InputStream in2=new CipherInputStream(in,cipher); JreepadTreeModel document; try { document=reader.read(in2); } catch ( IOException e) { throw new IOException("Password incorrect or read problem occurred"); } document.setFileType(JreepadPrefs.FILETYPE_XML_ENCRYPTED); document.setPassword(password); return document; }
Example 94
From project LVLPractice, under directory /src/com/android/vending/licensing/.
Source file: AESObfuscator.java

/** * @param salt an array of random bytes to use for each (un)obfuscation * @param applicationId application identifier, e.g. the package name * @param deviceId device identifier. Use as many sources as possible to create this unique identifier. */ public AESObfuscator(byte[] salt,String applicationId,String deviceId){ try { SecretKeyFactory factory=SecretKeyFactory.getInstance(KEYGEN_ALGORITHM); KeySpec keySpec=new PBEKeySpec((applicationId + deviceId).toCharArray(),salt,1024,256); SecretKey tmp=factory.generateSecret(keySpec); SecretKey secret=new SecretKeySpec(tmp.getEncoded(),"AES"); mEncryptor=Cipher.getInstance(CIPHER_ALGORITHM); mEncryptor.init(Cipher.ENCRYPT_MODE,secret,new IvParameterSpec(IV)); mDecryptor=Cipher.getInstance(CIPHER_ALGORITHM); mDecryptor.init(Cipher.DECRYPT_MODE,secret,new IvParameterSpec(IV)); } catch ( GeneralSecurityException e) { throw new RuntimeException("Invalid environment",e); } }
Example 95
From project OAuth2Android, under directory /src/org/gerstner/oauth2android/token/.
Source file: MacTokenTypeDefinition.java

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 96
From project Opal, under directory /opal-crypto/src/main/java/com/lyndir/lhunath/opal/crypto/.
Source file: CryptUtils.java

/** * Encrypt or decrypt the given data using the given key using the given cipher. * @param data The data to decrypt. * @param key The encryption key to decrypt the data with. * @param cipherTransformation The cipher to use for performing the operation. * @param blockBitSize The bit-length of the blocks the cipher should operate on. The key will be trimmed to this size. * @param mode {@code Cipher.ENCRYPT_MODE} or {@code Cipher.DECRYPT_MODE} * @return The decrypted version of the encrypted data as decrypted by the given key. * @throws IllegalBlockSizeException While encrypting without padding, the plain text data's length is not a multiple of the cipherblock size. * @throws BadPaddingException While decrypting with padding, the encrypted data was not padded during encryption. */ public static byte[] doCrypt(final byte[] data,final byte[] key,final String cipherTransformation,final int blockBitSize,final int mode) throws IllegalBlockSizeException, BadPaddingException { int blockByteSize=blockBitSize / Byte.SIZE; byte[] blockSizedKey=key; if (blockSizedKey.length != blockByteSize) { blockSizedKey=new byte[blockByteSize]; System.arraycopy(key,0,blockSizedKey,0,blockByteSize); } try { Cipher cipher=Cipher.getInstance(cipherTransformation); cipher.init(mode,new SecretKeySpec(blockSizedKey,"AES")); return cipher.doFinal(data); } catch ( NoSuchAlgorithmException e) { throw new IllegalStateException("Cipher transformation: " + cipherTransformation + ", is not valid or not supported by the provider.",e); } catch ( NoSuchPaddingException e) { throw new IllegalStateException("Cipher transformation: " + cipherTransformation + ", uses a padding scheme that is not valid or not supported by the provider.",e); } catch ( InvalidKeyException e) { throw logger.bug(e,"Key is inappropriate for cipher."); } }
Example 97
From project OpenID-Connect-Java-Spring-Server, under directory /openid-connect-common/src/main/java/org/mitre/jwt/encryption/impl/.
Source file: RsaDecrypter.java

@Override public byte[] decryptCipherText(Jwe jwe,byte[] contentEncryptionKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { byte[] iv=new byte[16]; iv=Base64.decodeBase64(jwe.getHeader().getInitializationVector()); String encMethod=jwe.getHeader().getEncryptionMethod(); if (encMethod.equals("A128CBC") || encMethod.equals("A256CBC")) { String mode=JweAlgorithms.getByName(encMethod); Cipher cipher=Cipher.getInstance("AES/" + mode + "/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(contentEncryptionKey,"AES"),new IvParameterSpec(iv)); byte[] clearText=cipher.doFinal(jwe.getCiphertext()); return clearText; } else { throw new IllegalArgumentException(jwe.getHeader().getEncryptionMethod() + " is not an implemented encryption method"); } }
Example 98
From project platform_external_oauth, under directory /core/src/main/java/net/oauth/signature/.
Source file: HMAC_SHA1.java

private byte[] computeSignature(String baseString) throws GeneralSecurityException, UnsupportedEncodingException { SecretKey key=null; synchronized (this) { if (this.key == null) { String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes=keyString.getBytes(ENCODING); this.key=new SecretKeySpec(keyBytes,MAC_NAME); } key=this.key; } Mac mac=Mac.getInstance(MAC_NAME); mac.init(key); byte[] text=baseString.getBytes(ENCODING); return mac.doFinal(text); }
Example 99
From project playframework-oauthprovider, under directory /app/net/oauth/signature/.
Source file: HMAC_SHA1.java

/** * Compute signature. * @param baseString the base string * @return the byte[] * @throws GeneralSecurityException the general security exception * @throws UnsupportedEncodingException the unsupported encoding exception */ private byte[] computeSignature(String baseString) throws GeneralSecurityException, UnsupportedEncodingException { SecretKey key=null; synchronized (this) { if (this.key == null) { String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes=keyString.getBytes(ENCODING); this.key=new SecretKeySpec(keyBytes,MAC_NAME); } key=this.key; } Mac mac=Mac.getInstance(MAC_NAME); mac.init(key); byte[] text=baseString.getBytes(ENCODING); return mac.doFinal(text); }
Example 100
From project signpost, under directory /signpost-core/src/main/java/oauth/signpost/signature/.
Source file: HmacSha1MessageSigner.java

@Override public String sign(HttpRequest request,HttpParameters requestParams) throws OAuthMessageSignerException { try { String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes=keyString.getBytes(OAuth.ENCODING); SecretKey key=new SecretKeySpec(keyBytes,MAC_NAME); Mac mac=Mac.getInstance(MAC_NAME); mac.init(key); String sbs=new SignatureBaseString(request,requestParams).generate(); OAuth.debugOut("SBS",sbs); byte[] text=sbs.getBytes(OAuth.ENCODING); return base64Encode(mac.doFinal(text)).trim(); } catch ( GeneralSecurityException e) { throw new OAuthMessageSignerException(e); } catch ( UnsupportedEncodingException e) { throw new OAuthMessageSignerException(e); } }
Example 101
From project syncany, under directory /syncany/src/org/syncany/config/.
Source file: Encryption.java

/** * bit must be dividable by 8. * @param password * @param bit */ public void init() throws ConfigException { try { this.key=new byte[keylength / 8]; MessageDigest msgDigest=MessageDigest.getInstance("SHA-256"); msgDigest.reset(); byte[] longkey=msgDigest.digest(password.getBytes("UTF-8")); if (longkey.length == key.length) { this.key=longkey; } else if (longkey.length > key.length) { System.arraycopy(longkey,0,key,0,key.length); } else if (longkey.length < key.length) { throw new RuntimeException("Invalid key length '" + keylength + "' bit; max 256 bit supported."); } this.keySpec=new SecretKeySpec(key,cipherStr); this.cipher=Cipher.getInstance(cipherStr); byte[] testBytes=new byte[]{1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9}; if (!Arrays.equals(decrypt(encrypt(testBytes)),testBytes)) { throw new ConfigException("Test encrypt/decrypt cycle failed."); } } catch ( Exception e) { throw new ConfigException("Invalid encryption parameters.",e); } }
Example 102
From project Tanks_1, under directory /src/org/apache/mina/proxy/handlers/http/ntlm/.
Source file: NTLMResponses.java

/** * Creates a DES encryption key from the given key material. * @param bytes A byte array containing the DES key material. * @param offset The offset in the given byte array at whichthe 7-byte key material starts. * @return A DES encryption key created from the key materialstarting at the specified offset in the given byte array. */ private static Key createDESKey(byte[] bytes,int offset){ byte[] keyBytes=new byte[7]; System.arraycopy(bytes,offset,keyBytes,0,7); byte[] material=new byte[8]; material[0]=keyBytes[0]; material[1]=(byte)(keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1); material[2]=(byte)(keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2); material[3]=(byte)(keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3); material[4]=(byte)(keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4); material[5]=(byte)(keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5); material[6]=(byte)(keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6); material[7]=(byte)(keyBytes[6] << 1); oddParity(material); return new SecretKeySpec(material,"DES"); }
Example 103
From project thinklab, under directory /src/main/java/org/integratedmodelling/thinklab/authentication/.
Source file: EncryptionManager.java

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 104
From project james-mime4j, under directory /storage/src/main/java/org/apache/james/mime4j/storage/.
Source file: CipherStorageProvider.java

public CipherStorageOutputStream(StorageOutputStream out,String algorithm,SecretKeySpec skeySpec) throws IOException { try { this.storageOut=out; this.algorithm=algorithm; this.skeySpec=skeySpec; Cipher cipher=Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE,skeySpec); this.cipherOut=new CipherOutputStream(out,cipher); } catch ( GeneralSecurityException e) { throw (IOException)new IOException().initCause(e); } }
Example 105
From project Newsreader, under directory /bundles/org.apache.mime4j/src/org/apache/james/mime4j/storage/.
Source file: CipherStorageProvider.java

public CipherStorageOutputStream(StorageOutputStream out,String algorithm,SecretKeySpec skeySpec) throws IOException { try { this.storageOut=out; this.algorithm=algorithm; this.skeySpec=skeySpec; Cipher cipher=Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE,skeySpec); this.cipherOut=new CipherOutputStream(out,cipher); } catch ( GeneralSecurityException e) { throw (IOException)new IOException().initCause(e); } }