Java Code Examples for javax.crypto.SecretKey

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 cas, under directory /cas-server-extension-clearpass/src/main/java/org/jasig/cas/extension/clearpass/.

Source file: EncryptedMapDecorator.java

  28 
vote

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 2

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

Source file: IdentityApplic.java

  24 
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 3

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

Source file: JCESecurityModule.java

  24 
vote

/** 
 * Generates new LMK keys
 * @exception SMException
 */
private void generateLMK() throws SMException {
  lmks.clear();
  try {
    for (int i=0; i <= LMK_PAIRS_NO; i++) {
      SecretKey lmkKey=(SecretKey)jceHandler.generateDESKey(LMK_KEY_LENGTH);
      spreadLMKVariants(lmkKey.getEncoded(),i);
    }
  }
 catch (  JCEHandlerException e) {
    throw new SMException("Can't generate Local Master Keys",e);
  }
}
 

Example 4

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

Source file: Master.java

  23 
vote

public byte[] generateRawKey(String algorithm){
  KeyGenerator keyGen;
  try {
    keyGen=KeyGenerator.getInstance(algorithm);
    SecretKey key=keyGen.generateKey();
    byte[] keyBytes=key.getEncoded();
    return keyBytes;
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 5

From project BF3-Battlelog, under directory /src/net/sf/andhsli/hotspotlogin/.

Source file: SimpleCrypto.java

  23 
vote

private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
  kgen.init(128,sr);
  SecretKey skey=kgen.generateKey();
  byte[] raw=skey.getEncoded();
  return raw;
}
 

Example 6

From project android-bankdroid, under directory /src/net/sf/andhsli/hotspotlogin/.

Source file: SimpleCrypto.java

  22 
vote

private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
  kgen.init(128,sr);
  SecretKey skey=kgen.generateKey();
  byte[] raw=skey.getEncoded();
  return raw;
}
 

Example 7

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

Source file: Encrypt.java

  22 
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 8

From project core_4, under directory /impl/src/main/java/org/ajax4jsf/util/base64/.

Source file: Codec.java

  22 
vote

/** 
 * @param p
 * @throws java.security.InvalidKeyException
 * @throws java.io.UnsupportedEncodingException
 * @throws java.security.spec.InvalidKeySpecException
 * @throws java.security.NoSuchAlgorithmException
 * @throws javax.crypto.NoSuchPaddingException
 */
public void setPassword(String p) throws FacesException {
  byte[] s={(byte)0xA9,(byte)0x9B,(byte)0xC8,(byte)0x32,(byte)0x56,(byte)0x34,(byte)0xE3,(byte)0x03};
  try {
    KeySpec keySpec=new DESKeySpec(p.getBytes("UTF8"));
    SecretKey key=SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
    e=Cipher.getInstance(key.getAlgorithm());
    d=Cipher.getInstance(key.getAlgorithm());
    e.init(Cipher.ENCRYPT_MODE,key);
    d.init(Cipher.DECRYPT_MODE,key);
  }
 catch (  Exception e) {
    throw new FacesException("Error set encryption key",e);
  }
}
 

Example 9

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/security/token/.

Source file: JobTokenSecretManager.java

  22 
vote

/** 
 * Add the job token of a job to cache
 * @param jobId the job that owns the token
 * @param token the job token
 */
public void addTokenForJob(String jobId,Token<JobTokenIdentifier> token){
  SecretKey tokenSecret=createSecretKey(token.getPassword());
synchronized (currentJobTokens) {
    currentJobTokens.put(jobId,tokenSecret);
  }
}
 

Example 10

From project droidparts, under directory /extra/src/org/droidparts/util/crypto/.

Source file: Crypter.java

  22 
vote

private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
  kgen.init(128,sr);
  SecretKey skey=kgen.generateKey();
  byte[] raw=skey.getEncoded();
  return raw;
}
 

Example 11

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

Source file: Util.java

  22 
vote

public static byte[] newAESKey(){
  try {
    KeyGenerator kgen=KeyGenerator.getInstance("AES");
    kgen.init(128);
    SecretKey skey=kgen.generateKey();
    return skey.getEncoded();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 

Example 12

From project Eclipse, under directory /com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/internal/.

Source file: SecureProperties.java

  22 
vote

private Cipher createCipher(int mode,byte[] salt) throws GeneralSecurityException {
  SecretKeyFactory keyFactory;
  keyFactory=SecretKeyFactory.getInstance(KEY_FACTORY);
  SecretKey key=keyFactory.generateSecret(password);
  PBEParameterSpec entropy=new PBEParameterSpec(salt,8);
  Cipher cipher=Cipher.getInstance(CIPHER);
  cipher.init(mode,key,entropy);
  return cipher;
}
 

Example 13

From project entando-core-engine, under directory /src/main/java/com/agiletec/aps/util/.

Source file: DefaultApsEncrypter.java

  22 
vote

public static Key getKey(){
  try {
    byte[] bytes=KEY_STRING.getBytes();
    DESedeKeySpec pass=new DESedeKeySpec(bytes);
    SecretKeyFactory skf=SecretKeyFactory.getInstance(TRIPLE_DES_KEY_SPEC);
    SecretKey s=skf.generateSecret(pass);
    return s;
  }
 catch (  Throwable t) {
    throw new RuntimeException("Error creating key",t);
  }
}
 

Example 14

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

Source file: Route53Util.java

  22 
vote

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 15

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

Source file: StringEncrypter.java

  22 
vote

private byte[] encrypt(String unencryptedString) throws InvalidKeySpecException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
  SecretKey key=keyFactory.generateSecret(keySpec);
  cipher.init(Cipher.ENCRYPT_MODE,key);
  byte[] cleartext=unencryptedString.getBytes(UNICODE_FORMAT);
  byte[] ciphertext=cipher.doFinal(cleartext);
  return ciphertext;
}
 

Example 16

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

Source file: UpdateEncryptionMethod.java

  22 
vote

public SearchableStringEncryptor(String password,String salt){
  String algorithm="PBEWithMD5AndDES";
  byte[] saltBytes=Hex.decode(salt);
  SecretKey secretKey=newSecretKey(algorithm,password);
  encryptor=newCipher(algorithm);
  initCipher(encryptor,Cipher.ENCRYPT_MODE,secretKey,saltBytes,1000);
  decryptor=newCipher(algorithm);
  initCipher(decryptor,Cipher.DECRYPT_MODE,secretKey,saltBytes,1000);
}
 

Example 17

From project jAPS2, under directory /src/com/agiletec/aps/util/.

Source file: DefaultApsEncrypter.java

  22 
vote

public static Key getKey(){
  try {
    byte[] bytes=KEY_STRING.getBytes();
    DESedeKeySpec pass=new DESedeKeySpec(bytes);
    SecretKeyFactory skf=SecretKeyFactory.getInstance(TRIPLE_DES_KEY_SPEC);
    SecretKey s=skf.generateSecret(pass);
    return s;
  }
 catch (  Throwable t) {
    throw new RuntimeException("Error creating key",t);
  }
}
 

Example 18

From project JavaJunction, under directory /src/main/java/edu/stanford/junction/extra/.

Source file: Encryption.java

  22 
vote

@Override public boolean beforeActivityCreate(){
  try {
    KeyGenerator kgen=KeyGenerator.getInstance("AES");
    kgen.init(128);
    SecretKey skey=kgen.generateKey();
    mKey=skey.getEncoded();
    init();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return true;
}
 

Example 19

From project lor-jamwiki, under directory /jamwiki-core/src/main/java/org/jamwiki/utils/.

Source file: Encryption.java

  22 
vote

/** 
 * Encrypt a String value using the DES encryption algorithm.
 * @param unencryptedBytes The unencrypted String value that is to be encrypted.
 * @return An encrypted version of the String that was passed to this method.
 */
private static String encrypt64(byte[] unencryptedBytes) throws GeneralSecurityException, UnsupportedEncodingException {
  if (unencryptedBytes == null || unencryptedBytes.length == 0) {
    throw new IllegalArgumentException("Cannot encrypt a null or empty byte array");
  }
  SecretKey key=createKey();
  Cipher cipher=Cipher.getInstance(key.getAlgorithm());
  cipher.init(Cipher.ENCRYPT_MODE,key);
  byte[] encryptedBytes=Base64.encodeBase64(cipher.doFinal(unencryptedBytes));
  return bytes2String(encryptedBytes);
}
 

Example 20

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

Source file: StringEncrypter.java

  22 
vote

public String encrypt(String unencryptedString) throws EncryptionException {
  if (unencryptedString == null || unencryptedString.trim().length() == 0)   throw new IllegalArgumentException("unencrypted string was null or empty");
  try {
    SecretKey key=keyFactory.generateSecret(keySpec);
    cipher.init(Cipher.ENCRYPT_MODE,key);
    byte[] cleartext=unencryptedString.getBytes(UNICODE_FORMAT);
    byte[] ciphertext=cipher.doFinal(cleartext);
    return encodeBase64(ciphertext);
  }
 catch (  Exception e) {
    throw new EncryptionException(e);
  }
}
 

Example 21

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

Source file: StringEncrypter.java

  22 
vote

public String encrypt(String unencryptedString) throws EncryptionException {
  if (unencryptedString == null || unencryptedString.trim().length() == 0)   throw new IllegalArgumentException("unencrypted string was null or empty");
  try {
    SecretKey key=keyFactory.generateSecret(keySpec);
    cipher.init(Cipher.ENCRYPT_MODE,key);
    byte[] cleartext=unencryptedString.getBytes(UNICODE_FORMAT);
    byte[] ciphertext=cipher.doFinal(cleartext);
    return encodeBase64(ciphertext);
  }
 catch (  Exception e) {
    throw new EncryptionException(e);
  }
}
 

Example 22

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

Source file: SimpleCrypto.java

  22 
vote

private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
  kgen.init(128,sr);
  SecretKey skey=kgen.generateKey();
  byte[] raw=skey.getEncoded();
  return raw;
}
 

Example 23

From project OAK, under directory /oak-library/src/main/java/oak/.

Source file: ObscuredSharedPreferences.java

  22 
vote

protected String encrypt(String value){
  try {
    final byte[] bytes=value != null ? value.getBytes(UTF8) : new byte[0];
    SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key=keyFactory.generateSecret(new PBEKeySpec(getSpecialCode()));
    Cipher pbeCipher=Cipher.getInstance("PBEWithMD5AndDES");
    pbeCipher.init(Cipher.ENCRYPT_MODE,key,new PBEParameterSpec(getAndroidId().getBytes(UTF8),20));
    return new String(Base64.encode(pbeCipher.doFinal(bytes),Base64.NO_WRAP),UTF8);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 24

From project Ohmage_Phone, under directory /src/edu/ucla/cens/pdc/libpdc/stream/.

Source file: DataEncryptor.java

  22 
vote

public void generateNewKey(){
  try {
    SecretKey key=EncryptionHelper.generateSymKey("TwoFish",256);
    _encrypt_key=key.getEncoded();
  }
 catch (  PDCEncryptionException ex) {
    throw new Error("Unable to generate new key",ex);
  }
}
 

Example 25

From project Ohmage_Server_2, under directory /src/edu/ucla/cens/pdc/libpdc/stream/.

Source file: DataEncryptor.java

  22 
vote

public void generateNewKey(){
  try {
    SecretKey key=EncryptionHelper.generateSymKey("TwoFish",256);
    _encrypt_key=key.getEncoded();
  }
 catch (  PDCEncryptionException ex) {
    throw new Error("Unable to generate new key",ex);
  }
}
 

Example 26

From project openengsb-framework, under directory /components/services/src/test/java/org/openengsb/core/services/.

Source file: GenericSecurePortTest.java

  22 
vote

@Test public void testManipulateMessage_shouldCauseVerificationException() throws Exception {
  MethodCallMessage secureRequest=prepareSecureRequest();
  SecretKey sessionKey=CipherUtils.generateKey("AES",128);
  EncodingType encryptedRequest=encodeAndEncrypt(secureRequest,sessionKey);
  logRequest(encryptedRequest);
  EncodingType manipulatedRequest=manipulateMessage(encryptedRequest);
  try {
    secureRequestHandler.filter(manipulatedRequest,new HashMap<String,Object>());
    fail("Exception expected");
  }
 catch (  FilterException e) {
    verify(requestHandler,never()).handleCall(any(MethodCall.class));
  }
}
 

Example 27

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

Source file: Security.java

  22 
vote

private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
  kgen.init(128,sr);
  SecretKey skey=kgen.generateKey();
  byte[] raw=skey.getEncoded();
  return raw;
}
 

Example 28

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

Source file: Crypto.java

  22 
vote

public static String decryptPassword() throws Exception {
  ObjectInputStream ois=new ObjectInputStream(new FileInputStream("keyfile"));
  DESKeySpec ks=new DESKeySpec((byte[])ois.readObject());
  SecretKeyFactory skf=SecretKeyFactory.getInstance("DES");
  SecretKey key=skf.generateSecret(ks);
  Cipher c=Cipher.getInstance("DES/CFB8/NoPadding");
  c.init(Cipher.DECRYPT_MODE,key,new IvParameterSpec((byte[])ois.readObject()));
  CipherInputStream cis=new CipherInputStream(new FileInputStream("ciphertext"),c);
  BufferedReader br=new BufferedReader(new InputStreamReader(cis));
  String decrypted=br.readLine();
  return decrypted;
}
 

Example 29

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

Source file: CryptoHelper.java

  22 
vote

/** 
 * @author Isaac Potoczny-Jones
 * @return null if failure, otherwise hex string version of key
 */
public static String generateMasterKey() throws NoSuchAlgorithmException {
  try {
    KeyGenerator keygen;
    keygen=KeyGenerator.getInstance("AES");
    keygen.init(256);
    SecretKey genDesKey=keygen.generateKey();
    return toHexString(genDesKey.getEncoded());
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(TAG,"generateMasterKey(): " + e.toString());
    throw e;
  }
}
 

Example 30

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

Source file: PasswordHash.java

  22 
vote

/** 
 */
public String createPasswordKey(char[] password,byte[] salt,int iterations) throws GeneralSecurityException {
  if (hashAlgorithm != null) {
    PBEKeySpec passwordKeySpec=new PBEKeySpec(password,salt,iterations,256);
    SecretKeyFactory secretKeyFactory=SecretKeyFactory.getInstance(hashAlgorithm);
    SecretKey passwordKey=secretKeyFactory.generateSecret(passwordKeySpec);
    passwordKeySpec.clearPassword();
    return BinTools.bin2hex(passwordKey.getEncoded());
  }
 else {
    PBKDF2Parameters params=new PBKDF2Parameters("HmacSHA1","ISO-8859-1",salt,iterations);
    PBKDF2 pbkdf2=new PBKDF2Engine(params);
    return BinTools.bin2hex(pbkdf2.deriveKey(new String(password)));
  }
}
 

Example 31

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

Source file: Launcher.java

  22 
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 32

From project sms-backup-plus, under directory /src/com/zegoggles/smssync/.

Source file: XOAuthConsumer.java

  22 
vote

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 33

From project SpoutcraftLauncher, under directory /src/main/java/org/spoutcraft/launcher/skin/components/.

Source file: LoginFrame.java

  22 
vote

private final static Cipher getCipher(int mode,String password) throws Exception {
  Random random=new Random(43287234L);
  byte[] salt=new byte[8];
  random.nextBytes(salt);
  PBEParameterSpec pbeParamSpec=new PBEParameterSpec(salt,5);
  SecretKey pbeKey=SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec(password.toCharArray()));
  Cipher cipher=Cipher.getInstance("PBEWithMD5AndDES");
  cipher.init(mode,pbeKey,pbeParamSpec);
  return cipher;
}
 

Example 34

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

Source file: AndroidAesBytesEncryptor.java

  22 
vote

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 35

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

Source file: AesBytesEncryptor.java

  22 
vote

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 36

From project springfaces, under directory /springfaces-mvc/src/main/java/org/springframework/springfaces/mvc/render/.

Source file: ClientFacesViewStateHandler.java

  22 
vote

private String encrypt(HttpServletRequest request,String value){
  try {
    byte[] bytes=value.getBytes();
    SecretKey secretKey=getSecretKey(request);
    byte[] initializationVector=createRandomInitializationVector();
    Cipher cipher=getCipher(Cipher.ENCRYPT_MODE,secretKey,new IvParameterSpec(initializationVector));
    byte[] mac=getMac(secretKey).doFinal(bytes);
    return HexString.toString(initializationVector) + HexString.toString(cipher.update(mac)) + HexString.toString(cipher.doFinal(bytes));
  }
 catch (  Exception e) {
    throw new IllegalStateException("Unable to encrypt input value",e);
  }
}
 

Example 37

From project springside, under directory /modules/core/src/main/java/org/springside/modules/security/utils/.

Source file: Cryptos.java

  22 
vote

/** 
 * ???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 38

From project springside4, under directory /modules/core/src/main/java/org/springside/modules/security/utils/.

Source file: Cryptos.java

  22 
vote

/** 
 * ???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 39

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

Source file: MasterSecretUtil.java

  22 
vote

private static byte[] generateEncryptionSecret(){
  try {
    KeyGenerator generator=KeyGenerator.getInstance("AES");
    generator.init(128);
    SecretKey key=generator.generateKey();
    return key.getEncoded();
  }
 catch (  NoSuchAlgorithmException ex) {
    Log.w("keyutil",ex);
    return null;
  }
}
 

Example 40

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

Source file: EncryptionManager.java

  22 
vote

public String encrypt(String unencryptedString) throws ThinklabValidationException {
  if (unencryptedString == null || unencryptedString.trim().length() == 0)   throw new IllegalArgumentException("unencrypted string was null or empty");
  try {
    SecretKey key=keyFactory.generateSecret(keySpec);
    cipher.init(Cipher.ENCRYPT_MODE,key);
    byte[] cleartext=unencryptedString.getBytes(UNICODE_FORMAT);
    byte[] ciphertext=cipher.doFinal(cleartext);
    BASE64Encoder base64encoder=new BASE64Encoder();
    return base64encoder.encode(ciphertext);
  }
 catch (  Exception e) {
    throw new ThinklabValidationException(e);
  }
}
 

Example 41

From project upm-android, under directory /src/com/u17od/upm/crypto/.

Source file: DESDecryptionService.java

  22 
vote

/** 
 * This method initialises a local decryption cipher, and decrypts the given string. It's here as a convenience method for backwards compatibility with the old DES  encryption algorithm pre 1.3
 * @param password
 * @param salt
 * @param ciphertext
 * @return The decrypted bytes
 * @throws NoSuchAlgorithmException 
 * @throws InvalidKeySpecException 
 * @throws NoSuchPaddingException 
 * @throws InvalidKeyException 
 * @throws InvalidAlgorithmParameterException 
 * @throws IllegalBlockSizeException 
 * @throws InvalidPasswordException 
 */
public static byte[] decrypt(char[] password,byte[] salt,byte[] ciphertext) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, InvalidPasswordException {
  PBEKeySpec pbeKeySpec=new PBEKeySpec(password);
  SecretKeyFactory keyFac=SecretKeyFactory.getInstance(PBEWithMD5AndDES);
  SecretKey secretKey=keyFac.generateSecret(pbeKeySpec);
  return decrypt(secretKey,salt,ciphertext);
}
 

Example 42

From project usergrid-stack, under directory /core/src/main/java/org/usergrid/utils/.

Source file: AESUtils.java

  22 
vote

public static synchronized String encrypt(String secret,String plainText){
  secret=substring(rightPad(secret,16),0,16);
  SecretKey key=new SecretKeySpec(secret.getBytes(),"AES");
  try {
    cipher.init(Cipher.ENCRYPT_MODE,key);
    byte[] cipherText=cipher.doFinal(plainText.getBytes());
    return new String(coder.encode(cipherText));
  }
 catch (  Exception e) {
    logger.error("Encryption error",e);
  }
  return null;
}
 

Example 43

From project wheelmap-android, under directory /wheelmap/wheelmap/src/main/java/oak/.

Source file: ObscuredSharedPreferences.java

  22 
vote

protected String encrypt(String value){
  try {
    final byte[] bytes=value != null ? value.getBytes(UTF8) : new byte[0];
    SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key=keyFactory.generateSecret(new PBEKeySpec(getSpecialCode()));
    Cipher pbeCipher=Cipher.getInstance("PBEWithMD5AndDES");
    pbeCipher.init(Cipher.ENCRYPT_MODE,key,new PBEParameterSpec(getAndroidId().getBytes(UTF8),20));
    return new String(Base64.encode(pbeCipher.doFinal(bytes),Base64.NO_WRAP),UTF8);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 44

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

Source file: Crypto.java

  21 
vote

/** 
 * Returns HmacSHA1 of input.
 * @param secret String to process.
 * @return Digest of hash.
 */
public static byte[] getHmacSha1(final byte[] secret){
  try {
    final String keyString=Config.i.get("crypto.key.hmacsha1",null);
    if (StringUtils.isBlank(keyString)) {
      throw new IllegalArgumentException("crypto.key.hmacsha1 not defined");
    }
    final SecretKey key=new SecretKeySpec(keyString.getBytes(),"HmacSHA1");
    final Mac m=Mac.getInstance("HmacSHA1");
    m.init(key);
    m.update(secret);
    return m.doFinal();
  }
 catch (  final NoSuchAlgorithmException e) {
    throw new UnsupportedOperationException(e);
  }
catch (  final InvalidKeyException e) {
    throw new UnsupportedOperationException(e);
  }
}
 

Example 45

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/oauth/signpost/signature/.

Source file: HmacSha1MessageSigner.java

  21 
vote

@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 46

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

Source file: AESObfuscator.java

  21 
vote

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 47

From project android_external_oauth, under directory /core/src/main/java/net/oauth/signature/.

Source file: HMAC_SHA1.java

  21 
vote

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 48

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

Source file: Pusher.java

  21 
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 49

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

Source file: AESObfuscator.java

  21 
vote

/** 
 * @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 50

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

Source file: DES.java

  21 
vote

/** 
 * Encrypts a byte array.
 * @param plainBytes the bytes to encrypt
 * @param encryptionKey the key to use in the encryption phase
 * @return the encrypted bytes.
 */
public static byte[] encrypt(final byte[] plainBytes,byte[] encryptionKey) throws Exception {
  if (plainBytes == null) {
    return null;
  }
  if (encryptionKey == null) {
    throw new IllegalArgumentException("the key can not be null");
  }
  byte[] cipherBytes=null;
  encryptionKey=paddingKey(encryptionKey,KEY_LENGTH,PADDING_VALUE);
  final KeySpec keySpec=new DESedeKeySpec(encryptionKey);
  final SecretKeyFactory keyFactory=SecretKeyFactory.getInstance(ALGORITHM);
  final Cipher cipher=Cipher.getInstance(ALGORITHM);
  final SecretKey key=keyFactory.generateSecret(keySpec);
  cipher.init(Cipher.ENCRYPT_MODE,key);
  cipherBytes=cipher.doFinal(plainBytes);
  return cipherBytes;
}
 

Example 51

From project chililog-server, under directory /src/main/java/org/chililog/server/common/.

Source file: CryptoUtils.java

  21 
vote

/** 
 * <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 52

From project dnieprov, under directory /src/org/dnieprov/driver/.

Source file: DnieSecureChannel.java

  21 
vote

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 53

From project en4j, under directory /NBPlatformApp/Synchronization/src/main/java/com/rubenlaguna/en4j/sync/.

Source file: EvernoteProtocolUtil.java

  21 
vote

private EvernoteProtocolUtil(){
  try {
    KeySpec keySpec=new PBEKeySpec("55xdfsfAxkioou546bnTrjk".toCharArray(),salt,iterationCount);
    SecretKey key=SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
    Cipher dcipher=Cipher.getInstance(key.getAlgorithm());
    AlgorithmParameterSpec paramSpec=new PBEParameterSpec(salt,iterationCount);
    dcipher.init(Cipher.DECRYPT_MODE,key,paramSpec);
    byte[] dec=new Base64().decode(consumerKey);
    byte[] utf8=dcipher.doFinal(dec);
    a=new String(utf8,"UTF8");
    dec=new Base64().decode(consumerSecret);
    utf8=dcipher.doFinal(dec);
    b=new String(utf8,"UTF8");
  }
 catch (  Exception ex) {
    Exceptions.printStackTrace(ex);
  }
}
 

Example 54

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

Source file: EncFSCrypto.java

  21 
vote

/** 
 * Derive password-based key from input/config parameters using PBKDF2
 * @param config Volume configuration
 * @param password Volume password
 * @return Derived PBKDF2 key + IV bits
 * @throws EncFSInvalidConfigException Unable to decode salt bytes
 * @throws EncFSUnsupportedException PBKDF2WithHmacSHA1 not supported by current runtime
 */
public static byte[] derivePasswordKey(EncFSConfig config,String password) throws EncFSInvalidConfigException, EncFSUnsupportedException {
  byte[] cipherSaltData;
  try {
    cipherSaltData=EncFSBase64.decode(config.getSaltStr());
  }
 catch (  IOException e) {
    throw new EncFSInvalidConfigException("Corrupt salt data in config");
  }
  SecretKeyFactory f;
  try {
    f=SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new EncFSUnsupportedException(e);
  }
  KeySpec ks=new PBEKeySpec(password.toCharArray(),cipherSaltData,config.getIterationCount(),config.getVolumeKeySize() + EncFSVolume.IV_LENGTH * 8);
  SecretKey pbkdf2Key=null;
  try {
    pbkdf2Key=f.generateSecret(ks);
  }
 catch (  InvalidKeySpecException e) {
    throw new EncFSInvalidConfigException(e);
  }
  return pbkdf2Key.getEncoded();
}
 

Example 55

From project evodroid, under directory /src/com/sonorth/evodroid/.

Source file: b2evolutionDB.java

  21 
vote

public static String encryptPassword(String clearText){
  try {
    DESKeySpec keySpec=new DESKeySpec(PASSWORD_SECRET.getBytes("UTF-8"));
    SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("DES");
    SecretKey key=keyFactory.generateSecret(keySpec);
    Cipher cipher=Cipher.getInstance("DES");
    cipher.init(Cipher.ENCRYPT_MODE,key);
    String encrypedPwd=Base64.encodeBytes(cipher.doFinal(clearText.getBytes("UTF-8")));
    return encrypedPwd;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return clearText;
}
 

Example 56

From project freemind, under directory /freemind/freemind/main/.

Source file: Tools.java

  21 
vote

/** 
 */
private void init(byte[] mSalt){
  if (mSalt != null) {
    this.salt=mSalt;
  }
  if (ecipher == null) {
    try {
      KeySpec keySpec=new PBEKeySpec(passPhrase,salt,iterationCount);
      SecretKey key=SecretKeyFactory.getInstance(mAlgorithm).generateSecret(keySpec);
      ecipher=Cipher.getInstance(mAlgorithm);
      dcipher=Cipher.getInstance(mAlgorithm);
      AlgorithmParameterSpec paramSpec=new PBEParameterSpec(salt,iterationCount);
      ecipher.init(Cipher.ENCRYPT_MODE,key,paramSpec);
      dcipher.init(Cipher.DECRYPT_MODE,key,paramSpec);
    }
 catch (    java.security.InvalidAlgorithmParameterException e) {
    }
catch (    java.security.spec.InvalidKeySpecException e) {
    }
catch (    javax.crypto.NoSuchPaddingException e) {
    }
catch (    java.security.NoSuchAlgorithmException e) {
    }
catch (    java.security.InvalidKeyException e) {
    }
  }
}
 

Example 57

From project gengweibo, under directory /src/net/oauth/signature/.

Source file: HMAC_SHA1.java

  21 
vote

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 58

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

Source file: Security.java

  21 
vote

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 59

From project hdiv, under directory /hdiv-core/src/main/java/org/hdiv/cipher/.

Source file: KeyFactory.java

  21 
vote

/** 
 * 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 60

From project isohealth, under directory /Oauth/java/core/commons/src/main/java/net/oauth/signature/.

Source file: HMAC_SHA1.java

  21 
vote

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 61

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

Source file: DigestMD5Base.java

  21 
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 62

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

Source file: OAuthGenerator.java

  21 
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 63

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

Source file: AESObfuscator.java

  21 
vote

/** 
 * @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 64

From project oreilly-ejb-6thedition-book-examples, under directory /ch05-encryption/src/main/java/org/jboss/ejb3/examples/ch05/encryption/.

Source file: EncryptionBean.java

  21 
vote

/** 
 * Initializes this service before it may handle requests
 * @throws Exception If some unexpected error occurred
 */
@PostConstruct public void initialize() throws Exception {
  log.info("Initializing, part of " + PostConstruct.class.getName() + " lifecycle");
  final String cipherAlgorithm=DEFAULT_ALGORITHM_CIPHER;
  final byte[] ciphersSalt=DEFAULT_SALT_CIPHERS;
  final int ciphersIterationCount=DEFAULT_ITERATION_COUNT_CIPHERS;
  final String ciphersPassphrase=this.getCiphersPassphrase();
  final KeySpec ciphersKeySpec=new PBEKeySpec(ciphersPassphrase.toCharArray(),ciphersSalt,ciphersIterationCount);
  final SecretKey ciphersKey=SecretKeyFactory.getInstance(cipherAlgorithm).generateSecret(ciphersKeySpec);
  final AlgorithmParameterSpec paramSpec=new PBEParameterSpec(ciphersSalt,ciphersIterationCount);
  this.encryptionCipher=Cipher.getInstance(ciphersKey.getAlgorithm());
  this.decryptionCipher=Cipher.getInstance(ciphersKey.getAlgorithm());
  encryptionCipher.init(Cipher.ENCRYPT_MODE,ciphersKey,paramSpec);
  decryptionCipher.init(Cipher.DECRYPT_MODE,ciphersKey,paramSpec);
  log.info("Initialized encryption cipher: " + this.encryptionCipher);
  log.info("Initialized decryption cipher: " + this.decryptionCipher);
  final String messageDigestAlgorithm=this.getMessageDigestAlgorithm();
  try {
    this.messageDigest=MessageDigest.getInstance(messageDigestAlgorithm);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException("Could not obtain the " + MessageDigest.class.getSimpleName() + " for algorithm: "+ messageDigestAlgorithm,e);
  }
  log.info("Initialized MessageDigest for one-way hashing: " + this.messageDigest);
}
 

Example 65

From project PDF-to-unusual-HTML, under directory /PDF-to-unusual-HTML/src/org/apache/pdfbox/pdmodel/encryption/.

Source file: PublicKeySecurityHandler.java

  21 
vote

private DERObject createDERForRecipient(byte[] in,X509Certificate cert) throws IOException, GeneralSecurityException {
  String s="1.2.840.113549.3.2";
  AlgorithmParameterGenerator algorithmparametergenerator=AlgorithmParameterGenerator.getInstance(s);
  AlgorithmParameters algorithmparameters=algorithmparametergenerator.generateParameters();
  ByteArrayInputStream bytearrayinputstream=new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1"));
  ASN1InputStream asn1inputstream=new ASN1InputStream(bytearrayinputstream);
  DERObject derobject=asn1inputstream.readObject();
  KeyGenerator keygenerator=KeyGenerator.getInstance(s);
  keygenerator.init(128);
  SecretKey secretkey=keygenerator.generateKey();
  Cipher cipher=Cipher.getInstance(s);
  cipher.init(1,secretkey,algorithmparameters);
  byte[] abyte1=cipher.doFinal(in);
  DEROctetString deroctetstring=new DEROctetString(abyte1);
  KeyTransRecipientInfo keytransrecipientinfo=computeRecipientInfo(cert,secretkey.getEncoded());
  DERSet derset=new DERSet(new RecipientInfo(keytransrecipientinfo));
  AlgorithmIdentifier algorithmidentifier=new AlgorithmIdentifier(new DERObjectIdentifier(s),derobject);
  EncryptedContentInfo encryptedcontentinfo=new EncryptedContentInfo(PKCSObjectIdentifiers.data,algorithmidentifier,deroctetstring);
  EnvelopedData env=new EnvelopedData(null,derset,encryptedcontentinfo,null);
  ContentInfo contentinfo=new ContentInfo(PKCSObjectIdentifiers.envelopedData,env);
  return contentinfo.getDERObject();
}
 

Example 66

From project platform_external_oauth, under directory /core/src/main/java/net/oauth/signature/.

Source file: HMAC_SHA1.java

  21 
vote

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 67

From project playframework-oauthprovider, under directory /app/net/oauth/signature/.

Source file: HMAC_SHA1.java

  21 
vote

/** 
 * 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 68

From project SeriesGuide, under directory /SeriesGuide/src/com/battlelancer/seriesguide/util/.

Source file: SimpleCrypto.java

  21 
vote

private static byte[] getRawKey(Context context) throws Exception {
  KeyGenerator kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
  SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
  String seed=prefs.getString(SeriesGuidePreferences.KEY_SECURE,null);
  byte[] seedBytes;
  if (seed == null) {
    seedBytes=sr.generateSeed(16);
    seed=toHex(seedBytes);
    prefs.edit().putString(SeriesGuidePreferences.KEY_SECURE,seed).commit();
  }
 else {
    seedBytes=toByte(seed);
  }
  sr.setSeed(seedBytes);
  kgen.init(128,sr);
  SecretKey skey=kgen.generateKey();
  byte[] raw=skey.getEncoded();
  return raw;
}
 

Example 69

From project signpost, under directory /signpost-core/src/main/java/oauth/signpost/signature/.

Source file: HmacSha1MessageSigner.java

  21 
vote

@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 70

From project twitter-2-weibo, under directory /core/src/main/java/weibo4j/.

Source file: Oauth.java

  21 
vote

public String parseSignedRequest(String signed_request) throws IOException, InvalidKeyException, NoSuchAlgorithmException {
  String[] t=signed_request.split("\\.",2);
  int padding=(4 - t[0].length() % 4);
  for (int i=0; i < padding; i++)   t[0]+="=";
  String part1=t[0].replace("-","+").replace("_","/");
  SecretKey key=new SecretKeySpec(WeiboConfig.getValue("client_SERCRET").getBytes(),"hmacSHA256");
  Mac m;
  m=Mac.getInstance("hmacSHA256");
  m.init(key);
  m.update(t[1].getBytes());
  String part1Expect=BASE64Encoder.encode(m.doFinal());
  sun.misc.BASE64Decoder decode=new sun.misc.BASE64Decoder();
  String s=new String(decode.decodeBuffer(t[1]));
  if (part1.equals(part1Expect)) {
    return ts(s);
  }
 else {
    return null;
  }
}
 

Example 71

From project upm-swing, under directory /src/com/_17od/upm/crypto/.

Source file: DESDecryptionService.java

  21 
vote

private static byte[] process(char[] password,int mode,byte[] salt,byte[] plainText) throws CryptoException {
  byte[] retVal=null;
  try {
    PBEKeySpec pbeKeySpec=new PBEKeySpec(password);
    SecretKeyFactory keyFac=SecretKeyFactory.getInstance(PBEWithMD5AndDES);
    SecretKey secreyKey=keyFac.generateSecret(pbeKeySpec);
    PBEParameterSpec pbeParamSpec=new PBEParameterSpec(salt,20);
    Cipher desDecryptionCipher=Cipher.getInstance(PBEWithMD5AndDES);
    desDecryptionCipher.init(mode,secreyKey,pbeParamSpec);
    retVal=desDecryptionCipher.doFinal(plainText);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new CryptoException(e);
  }
catch (  IllegalBlockSizeException e) {
    throw new CryptoException(e);
  }
catch (  BadPaddingException e) {
    throw new CryptoException(e);
  }
catch (  NoSuchPaddingException e) {
    throw new CryptoException(e);
  }
catch (  InvalidKeySpecException e) {
    throw new CryptoException(e);
  }
catch (  InvalidKeyException e) {
    throw new CryptoException(e);
  }
catch (  InvalidAlgorithmParameterException e) {
    throw new CryptoException(e);
  }
  return retVal;
}
 

Example 72

From project warlock2, under directory /core/cc.warlock.core/src/main/cc/warlock/core/configuration/.

Source file: Account.java

  21 
vote

public DESEncrypter(String password){
  try {
    KeySpec keySpec=new PBEKeySpec(password.toCharArray(),salt,iterations);
    SecretKey key=SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
    eCipher=Cipher.getInstance(key.getAlgorithm());
    dCipher=Cipher.getInstance(key.getAlgorithm());
    AlgorithmParameterSpec paramSpec=new PBEParameterSpec(salt,iterations);
    eCipher.init(Cipher.ENCRYPT_MODE,key,paramSpec);
    dCipher.init(Cipher.DECRYPT_MODE,key,paramSpec);
  }
 catch (  InvalidKeyException e) {
    e.printStackTrace();
  }
catch (  InvalidKeySpecException e) {
    e.printStackTrace();
  }
catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
catch (  NoSuchPaddingException e) {
    e.printStackTrace();
  }
catch (  InvalidAlgorithmParameterException e) {
    e.printStackTrace();
  }
}
 

Example 73

From project Wordpress-Android-App, under directory /src/org/wordpress/android/.

Source file: WordPressDB.java

  21 
vote

public static String encryptPassword(String clearText){
  try {
    DESKeySpec keySpec=new DESKeySpec(PASSWORD_SECRET.getBytes("UTF-8"));
    SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("DES");
    SecretKey key=keyFactory.generateSecret(keySpec);
    Cipher cipher=Cipher.getInstance("DES");
    cipher.init(Cipher.ENCRYPT_MODE,key);
    String encrypedPwd=Base64.encodeBytes(cipher.doFinal(clearText.getBytes("UTF-8")));
    return encrypedPwd;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return clearText;
}
 

Example 74

From project Zypr-Reference-Client---Java, under directory /source/net/zypr/gui/.

Source file: Configuration.java

  21 
vote

private Configuration(){
  super();
  _propertiesFilePath=System.getProperty("user.home") + File.separator + ".zypr"+ File.separator+ "zypr.xml";
  load();
  try {
    byte[] salt={(byte)0xA9,(byte)0x9B,(byte)0xC8,(byte)0x32,(byte)0x56,(byte)0x35,(byte)0xE3,(byte)0x03};
    char[] passPhrase={(char)42,'R',(char)42,'A',(char)42,'N',(char)42,'A',(char)42,'C',(char)42,'N',(char)42,'A',(char)42,'V',(char)42,'I',(char)42,'K',(char)42};
    KeySpec keySpec=new PBEKeySpec(passPhrase,salt,42);
    SecretKey secretKey=SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
    _cipherEncrypter=Cipher.getInstance(secretKey.getAlgorithm());
    _cipherDecrypter=Cipher.getInstance(secretKey.getAlgorithm());
    AlgorithmParameterSpec algorithmParameterSpec=new PBEParameterSpec(salt,42);
    _cipherEncrypter.init(Cipher.ENCRYPT_MODE,secretKey,algorithmParameterSpec);
    _cipherDecrypter.init(Cipher.DECRYPT_MODE,secretKey,algorithmParameterSpec);
  }
 catch (  Exception exception) {
    _logger.error("",exception);
  }
}
 

Example 75

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

Source file: ClearText.java

  19 
vote

public CipherText encrypt(SecretKey secretKey){
  try {
    Cipher cipher=Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE,secretKey);
    byte[] encrypted=cipher.doFinal(bytes);
    return new CipherText(encrypted);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 76

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 77

From project orientdb, under directory /core/src/main/java/com/orientechnologies/orient/core/security/.

Source file: OSecurityManager.java

  19 
vote

public SecretKey generateKey(final String iAlgorithm,final int iKeySize){
  KeyGenerator kg;
  try {
    kg=KeyGenerator.getInstance(iAlgorithm);
    kg.init(iKeySize);
    return kg.generateKey();
  }
 catch (  Exception e) {
    throw new OSecurityException("Error on generating key for algorithm: " + iAlgorithm,e);
  }
}
 

Example 78

From project tinfoil-sms, under directory /branches/crypto-dev/strippedcastle/src/org/spongycastle/jcajce/provider/asymmetric/ec/.

Source file: KeyAgreementSpi.java

  19 
vote

protected SecretKey engineGenerateSecret(String algorithm) throws NoSuchAlgorithmException {
  byte[] secret=bigIntToBytes(result);
  if (kdf != null) {
    if (!algorithms.containsKey(algorithm)) {
      throw new NoSuchAlgorithmException("unknown algorithm encountered: " + algorithm);
    }
    int keySize=((Integer)algorithms.get(algorithm)).intValue();
    DHKDFParameters params=new DHKDFParameters(new DERObjectIdentifier(algorithm),keySize,secret);
    byte[] keyBytes=new byte[keySize / 8];
    kdf.init(params);
    kdf.generateBytes(keyBytes,0,keyBytes.length);
    secret=keyBytes;
  }
 else {
  }
  return new SecretKeySpec(secret,algorithm);
}
 

Example 79

From project uaa, under directory /common/src/test/java/org/cloudfoundry/identity/uaa/authentication/.

Source file: RubyUserTokenTests.java

  19 
vote

/** 
 * @param token the token string containing the ruby-marshalled username, expiry time and HMAC signature
 * @param key Used to validate the signature of the token.
 * @return a UserToken instance containing the data
 * @throws SignatureException if the signature in the token string does not match the one calculated using thesupplied key.
 */
public static UserToken decode(String token,SecretKey key) throws SignatureException {
  ByteArrayInputStream bytes=new ByteArrayInputStream(Hex.decode(token));
  try {
    UnmarshalStream stream=new UnmarshalStream(Ruby.getGlobalRuntime(),bytes,null,false);
    IRubyObject object=stream.unmarshalObject();
    Assert.isInstanceOf(RubyArray.class,object);
    RubyArray array=(RubyArray)object;
    Assert.isTrue(array.size() == 3);
    String username=(String)array.get(0);
    Long validUntil=(Long)array.get(1);
    ByteList sigBytes=((RubyString)array.eltOk(2)).getByteList();
    UserToken ut=new UserToken(username,validUntil,key);
    if (!Arrays.equals(ut.signature,sigBytes.unsafeBytes())) {
      throw new SignatureException("Signature is invalid for username = " + username + ", validUntil "+ validUntil);
    }
    return ut;
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
}