Java Code Examples for javax.crypto.spec.SecretKeySpec

The following examples show how to use javax.crypto.spec.SecretKeySpec. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Bytecoder   Source File: TlsPrfGenerator.java    License: Apache License 2.0 6 votes vote down vote up
SecretKey engineGenerateKey0(boolean tls12) {
    if (spec == null) {
        throw new IllegalStateException(
            "TlsPrfGenerator must be initialized");
    }
    SecretKey key = spec.getSecret();
    byte[] secret = (key == null) ? null : key.getEncoded();
    try {
        byte[] labelBytes = spec.getLabel().getBytes(UTF_8);
        int n = spec.getOutputLength();
        byte[] prfBytes = (tls12 ?
            doTLS12PRF(secret, labelBytes, spec.getSeed(), n,
                spec.getPRFHashAlg(), spec.getPRFHashLength(),
                spec.getPRFBlockSize()) :
            doTLS10PRF(secret, labelBytes, spec.getSeed(), n));
        return new SecretKeySpec(prfBytes, "TlsPrf");
    } catch (GeneralSecurityException e) {
        throw new ProviderException("Could not generate PRF", e);
    }
}
 
Example 2
Source Project: FHIR   Source File: BulkDataExportUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchJobIdEnDecryption() throws Exception {
    String jobId = "100";
    SecretKeySpec secretKey = BulkDataConfigUtil.getBatchJobIdEncryptionKey("test-key");
    assertNotNull(secretKey);

    String encryptedJobId = BulkDataExportUtil.encryptBatchJobId(jobId, secretKey);
    assertNotNull(encryptedJobId);
    assertFalse(encryptedJobId.equals(jobId));

    encryptedJobId = URLDecoder.decode(encryptedJobId, StandardCharsets.UTF_8.toString());
    assertNotNull(encryptedJobId);

    String decryptedJobId = BulkDataExportUtil.decryptBatchJobId(encryptedJobId, secretKey);
    assertNotNull(decryptedJobId);
    assertEquals(decryptedJobId, jobId);
}
 
Example 3
Source Project: t-io   Source File: ACEUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 加密
 * @param sSrc
 * @param sKey
 * @param ivStr 使用CBC模式,需要一个向量iv,可增加加密算法的强度
 * @return
 * @throws Exception
 */
@SuppressWarnings("restriction")
public static String encrypt(String sSrc, String sKey, String ivStr) throws Exception {
	// 判断Key是否正确
	if (sKey == null) {
		throw new Exception("Key为空");
	}
	// 判断Key是否为16位
	if (sKey.length() != 16) {
		throw new Exception("Key长度不是16位");
	}
	byte[] raw = sKey.getBytes();
	SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
	Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
	IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
	cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
	byte[] encrypted = cipher.doFinal(sSrc.getBytes());

	return new sun.misc.BASE64Encoder().encode(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
 
Example 4
Source Project: burp-api-drops   Source File: AES.java    License: Apache License 2.0 6 votes vote down vote up
public static String decrypt(String AESkey, String AESIV, Boolean baseEncode, String AESMode, String cipherText)
  throws Exception
{
  byte[] keyValue = AESkey.getBytes();
  Key skeySpec = new SecretKeySpec(keyValue, "AES");
  byte[] iv = AESIV.getBytes();
  IvParameterSpec ivSpec = new IvParameterSpec(iv);
  
  String cmode = AESMode;
  
  Cipher cipher = Cipher.getInstance(cmode);
  if (cmode.contains("CBC")) {
    cipher.init(2, skeySpec, ivSpec);
  } else {
    cipher.init(2, skeySpec);
  }
  byte[] cipherbytes = cipherText.getBytes();
  if (baseEncode) {
    cipherbytes = (new BASE64Decoder()).decodeBuffer(cipherText);
  }
  byte[] original = cipher.doFinal(cipherbytes);
  return new String(original);
}
 
Example 5
private byte[] getValueFromView() {

        final int lockState = mLockStates.getSelectedItemPosition();
        final String oldLockCode = mOldLockCode.getText().toString();
        final String newLockCode = mNewLockCode.getText().toString();
        final byte [] data;

        if(lockState == 0 || lockState == 2){
            data = new byte[1];
            data[0] = (byte)lockState;
            return data;
        } else {
            data = new byte[17]; //lockstate + security key
            data[0] = (byte)(lockState-1);

            final byte [] oldLockCodeBytes = new byte [16];
            ParserUtils.setByteArrayValue(oldLockCodeBytes, 0, oldLockCode);

            final byte [] newLockCodeBytes = new byte[16];
            ParserUtils.setByteArrayValue(newLockCodeBytes, 0, newLockCode);

            final byte [] encryptedLockCode = ParserUtils.aes128Encrypt(newLockCodeBytes, new SecretKeySpec(oldLockCodeBytes, "AES"));
            System.arraycopy(encryptedLockCode, 0, data, 1, encryptedLockCode.length);
            return data;
        }
    }
 
Example 6
/**
 * Creates a CachedContentIndex which works on the index file in the given cacheDir.
 *
 * @param cacheDir Directory where the index file is kept.
 * @param secretKey 16 byte AES key for reading, and optionally writing, the cache index.
 * @param encrypt Whether the index will be encrypted when written. Must be false if {@code
 *     secretKey} is null.
 */
public CachedContentIndex(File cacheDir, byte[] secretKey, boolean encrypt) {
  this.encrypt = encrypt;
  if (secretKey != null) {
    Assertions.checkArgument(secretKey.length == 16);
    try {
      cipher = getCipher();
      secretKeySpec = new SecretKeySpec(secretKey, "AES");
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
      throw new IllegalStateException(e); // Should never happen.
    }
  } else {
    Assertions.checkState(!encrypt);
    cipher = null;
    secretKeySpec = null;
  }
  keyToContent = new HashMap<>();
  idToKey = new SparseArray<>();
  atomicFile = new AtomicFile(new File(cacheDir, FILE_NAME));
}
 
Example 7
Source Project: bop-bitcoin-client   Source File: ExtendedKey.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] encrypt (String passphrase, boolean production) throws ValidationException
{
	try
	{
		byte[] key = SCrypt.generate (passphrase.getBytes ("UTF-8"), BITCOIN_SEED, 16384, 8, 8, 32);
		SecretKeySpec keyspec = new SecretKeySpec (key, "AES");
		Cipher cipher = Cipher.getInstance ("AES/CBC/PKCS5Padding", "BC");
		cipher.init (Cipher.ENCRYPT_MODE, keyspec);
		byte[] iv = cipher.getIV ();
		byte[] c = cipher.doFinal (serialize (production).getBytes ());
		byte[] result = new byte[iv.length + c.length];
		System.arraycopy (iv, 0, result, 0, iv.length);
		System.arraycopy (c, 0, result, iv.length, c.length);
		return result;
	}
	catch ( UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException
			| IllegalBlockSizeException | BadPaddingException e )
	{
		throw new ValidationException (e);
	}
}
 
Example 8
Source Project: snowblossom   Source File: CipherUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static ByteString decryptSymmetric(SymmetricKey key, ByteString cipher_data)
  throws ValidationException
{
  try
  {
    if (key.getAlgoSet() == 0)
    {
      byte[] iv_bytes = cipher_data.substring(0, SYM_IV_SIZE_0).toByteArray();
  
      Key k_spec = new SecretKeySpec(key.getKey().toByteArray(), "AES");
      Cipher cipher = Cipher.getInstance(SYM_ENCRYPTION_MODE_0);
      cipher.init(Cipher.DECRYPT_MODE, k_spec, new IvParameterSpec(iv_bytes));

      byte[] plain_data = cipher.doFinal(cipher_data.substring(SYM_IV_SIZE_0).toByteArray());
      return ByteString.copyFrom(plain_data);

    }
    throw new ValidationException("Unknown algo_set: " + key.getAlgoSet());

  }
  catch(java.security.GeneralSecurityException e)
  {
    throw new ValidationException(e);
  }

}
 
Example 9
Source Project: j2objc   Source File: CipherTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testCipher_getInstance_WrongType_Failure() throws Exception {
    Provider mockProviderInvalid = new MockProvider("MockProviderInvalid") {
        public void setup() {
            put("Cipher.FOO", Object.class.getName());
        }
    };

    Security.addProvider(mockProviderInvalid);
    try {
        Cipher c = Cipher.getInstance("FOO");
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(new byte[16], "FOO"));
        fail("Should not find any matching providers; found: " + c);
    } catch (ClassCastException expected) {
    } finally {
        Security.removeProvider(mockProviderInvalid.getName());
    }
}
 
Example 10
private boolean hmacEqual(byte[] sig, byte[] message, Key key) throws NoSuchAlgorithmException, InvalidKeyException {
    // See https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/
    // This randomizes the byte order to make timing attacks more difficult.
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(key);
    byte[] calculatedSig = mac.doFinal(message);

    // Generate a random key for use in comparison
    byte[] randomKey = new byte[32];
    RANDOM.nextBytes(randomKey);

    // Then generate two HMACs for the different signatures found
    Mac mac2 = Mac.getInstance("HmacSHA256");
    mac2.init(new SecretKeySpec(randomKey, "HmacSHA256"));
    byte[] clientSig = mac2.doFinal(sig);
    mac2.reset();
    byte[] realSig = mac2.doFinal(calculatedSig);

    return MessageDigest.isEqual(clientSig, realSig);
}
 
Example 11
Source Project: blockchain-java   Source File: WalletUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 保存钱包数据
 */
private void saveToDisk(Wallets wallets) {
    try {
        if (wallets == null) {
            log.error("Fail to save wallet to file ! wallets is null ");
            throw new Exception("ERROR: Fail to save wallet to file !");
        }
        SecretKeySpec sks = new SecretKeySpec(CIPHER_TEXT, ALGORITHM);
        // Create cipher
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, sks);
        SealedObject sealedObject = new SealedObject(wallets, cipher);
        // Wrap the output stream
        @Cleanup CipherOutputStream cos = new CipherOutputStream(
                new BufferedOutputStream(new FileOutputStream(WALLET_FILE)), cipher);
        @Cleanup ObjectOutputStream outputStream = new ObjectOutputStream(cos);
        outputStream.writeObject(sealedObject);
    } catch (Exception e) {
        log.error("Fail to save wallet to disk !", e);
        throw new RuntimeException("Fail to save wallet to disk !");
    }
}
 
Example 12
Source Project: aws-dynamodb-encryption-java   Source File: Hkdf.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initializes this Hkdf with input keying material and a salt. If <code>
 * salt</code> is <code>null</code> or of length 0, then a default salt of
 * HashLen zeros will be used (where HashLen is the length of the return
 * value of the supplied algorithm).
 *
 * @param salt
 *            the salt used for key extraction (optional)
 * @param ikm
 *            the Input Keying Material
 */
public void init(final byte[] ikm, final byte[] salt) {
    byte[] realSalt = (salt == null) ? EMPTY_ARRAY : salt.clone();
    byte[] rawKeyMaterial = EMPTY_ARRAY;
    try {
        Mac extractionMac = Mac.getInstance(algorithm, provider);
        if (realSalt.length == 0) {
            realSalt = new byte[extractionMac.getMacLength()];
            Arrays.fill(realSalt, (byte) 0);
        }
        extractionMac.init(new SecretKeySpec(realSalt, algorithm));
        rawKeyMaterial = extractionMac.doFinal(ikm);
        SecretKeySpec key = new SecretKeySpec(rawKeyMaterial, algorithm);
        Arrays.fill(rawKeyMaterial, (byte) 0);  // Zeroize temporary array
        unsafeInitWithoutKeyExtraction(key);
    } catch (GeneralSecurityException e) {
        // We've already checked all of the parameters so no exceptions
        // should be possible here.
        throw new RuntimeException("Unexpected exception", e);
    } finally {
        Arrays.fill(rawKeyMaterial, (byte) 0);  // Zeroize temporary array
    }
}
 
Example 13
Source Project: mPass   Source File: AesEncryptProvider.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 构造函数
 *
 * @param password
 */
public AesEncryptProvider(String password) {
    super(password);
    String str = new StringBuffer(password).append(PASSWORD_DEFAULT).toString();
    String key = str.substring(0, 16);
    String iv = str.substring(16, 32);
    try {
        this.encryptor = Cipher.getInstance(AES_CBC_ALGORITHM);
        this.decryptor = Cipher.getInstance(AES_CBC_ALGORITHM);
    } catch (NoSuchAlgorithmException e1) {
        log.error("Not a valid encryption algorithm", e1);
        throw new IllegalArgumentException("Not a valid encryption algorithm", e1);
    } catch (NoSuchPaddingException e2) {
        log.error("Not a valid encryption algorithm", e2);
        throw new IllegalStateException("Should not happen", e2);
    }
    this.secretKey = new SecretKeySpec(key.getBytes(CHARSET_DEFAULT), ENCRYPT_AES);
    this.ivParam = new IvParameterSpec(iv.getBytes(CHARSET_DEFAULT));
}
 
Example 14
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
Example 15
public static Cipher getCipher(final boolean encrypt, final byte[] kek)
        throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, InvalidAlgorithmParameterException {
    GXByteBuffer iv = new GXByteBuffer();
    // iv.set(IV);

    // iv.set(p.getSystemTitle());
    // iv.setUInt32(p.getInvocationCounter());
    SecretKeySpec eks = new SecretKeySpec(kek, "AES");
    Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
    int mode;
    if (encrypt) {
        mode = Cipher.ENCRYPT_MODE;
    } else {
        mode = Cipher.DECRYPT_MODE;
    }
    c.init(mode, eks, new GCMParameterSpec(12 * 8, iv.array()));
    return c;
}
 
Example 16
Source Project: couchbase-jvm-core   Source File: ShaSaslClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generate the HMAC with the given SHA algorithm
 */
private byte[] hmac(byte[] key, byte[] data) {
    try {
        final Mac mac = Mac.getInstance(hmacAlgorithm);
        mac.init(new SecretKeySpec(key, mac.getAlgorithm()));
        return mac.doFinal(data);
    } catch (InvalidKeyException e) {
        if (key.length == 0) {
            throw new UnsupportedOperationException("This JVM does not support empty HMAC keys (empty passwords). "
                    + "Please set a bucket password or upgrade your JVM.");
        } else {
            throw new RuntimeException("Failed to generate HMAC hash for password", e);
        }
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}
 
Example 17
Source Project: taoshop   Source File: AESUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 解密
 * @param encryptBytes
 * @param decryptKey
 * @return
 * @throws Exception
 */
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    //防止linux下 随机生成key
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
    secureRandom.setSeed(decryptKey.getBytes());
    kgen.init(128, secureRandom);
    SecretKey secretKey = kgen.generateKey();
    byte[] enCodeFormat = secretKey.getEncoded();
    SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
    Cipher cipher = Cipher.getInstance("AES");// 创建密码器
    cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
    byte[] result = cipher.doFinal(encryptBytes);

    return new String(result);
}
 
Example 18
Source Project: DiscordSRV   Source File: DebugUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Encrypt the given `data` byte array with the given `key` (16 bytes, 128-bit)
 * @param key the key to encrypt data with
 * @param data the data to encrypt
 * @return the randomly generated IV + the encrypted data with no separator ([iv..., encryptedData...])
 */
public static byte[] encrypt(byte[] key, byte[] data) {
    try {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        byte[] iv = new byte[cipher.getBlockSize()];
        RANDOM.nextBytes(iv);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
        byte[] encrypted = cipher.doFinal(data);
        return ArrayUtils.addAll(iv, encrypted);
    } catch (InvalidKeyException e) {
        if (e.getMessage().toLowerCase().contains("illegal key size")) {
            throw new RuntimeException(e.getMessage(), e);
        } else {
            e.printStackTrace();
        }
        return null;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
 
Example 19
protected SecretKey engineGenerateKey() {
    if (spec == null) {
        throw new IllegalStateException(
            "TlsRsaPremasterSecretGenerator must be initialized");
    }
    byte[] b = spec.getEncodedSecret();
    if (b == null) {
        if (random == null) {
            random = new SecureRandom();
        }
        b = new byte[48];
        random.nextBytes(b);
        b[0] = (byte)spec.getMajorVersion();
        b[1] = (byte)spec.getMinorVersion();
    }

    return new SecretKeySpec(b, "TlsRsaPremasterSecret");
}
 
Example 20
Source Project: tomcat-vault   Source File: EncryptionUtil.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] decrypt(byte[] encryptedData, KeyPair keypair, SecretKey key) throws Exception {
    // Get the KeyGenerator
    KeyGenerator kgen = KeyGenerator.getInstance(this.encryptionAlgorithm);
    kgen.init(keySize);

    byte[] publicKeyEncoded = keypair.getPrivate().getEncoded();

    SecretKeySpec skeySpec = new SecretKeySpec(key.getEncoded(), encryptionAlgorithm);

    // Instantiate the cipher
    Cipher cipher = Cipher.getInstance(encryptionAlgorithm);

    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] original = cipher.doFinal(encryptedData);
    return original;
}
 
Example 21
Source Project: j2objc   Source File: SecretKeySpecTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * getEncoded() method testing. Tests that returned array is equal to the
 * array specified in the constructor. Checks that modification
 * of returned array does not affect the internal array.
 */
public void testGetEncoded() {
    byte[] key = new byte[] {1, 2, 3, 4, 5};
    String algorithm = "Algorithm";

    SecretKeySpec ks = new SecretKeySpec(key, algorithm);
    byte[] result = ks.getEncoded();
    if (! Arrays.equals(key, result)) {
        fail("The returned key does not equal to the specified "
                + "in the constructor.");
    }
    result[0] ++;
    assertFalse("The change of returned by getEncoded() method key "
                + "should not cause the change of internal array.",
                result[0] == ks.getEncoded()[0]);

    // Regression for HARMONY-78
    int offset = 1;
    int len = 4;
    SecretKeySpec sks = new SecretKeySpec(key, offset, len, algorithm);
    assertEquals("Key length is incorrect", len, sks.getEncoded().length);
}
 
Example 22
Source Project: xian   Source File: CodingUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * AES解密
 */
public static String decryptToAes(String content, String pwd) {
    if (StringUtil.isEmpty(content) || StringUtil.isEmpty(pwd)) {
        return null;
    }
    try {
        SecretKeySpec key = new SecretKeySpec(getKey(pwd).getEncoded(), AES);
        Cipher cipher = Cipher.getInstance(AES);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] result = cipher.doFinal(hexToByte(content));
        return new String(result);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
        LOG.error(e);
    }
    return null;
}
 
Example 23
/**
 * Obtains an initialized DES cipher.
 *
 * @param encryptMode true if encryption is desired, false is decryption
 * is desired.
 * @param key the bytes for the DES key
 * @param ivBytes the initial vector bytes
 */
private final Cipher getInitializedDes(boolean encryptMode, byte[] key,
                                      byte[] ivBytes)
    throws  GSSException  {


    try {
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        SecretKey jceKey = (SecretKey) (new SecretKeySpec(key, "DES"));

        Cipher desCipher = Cipher.getInstance("DES/CBC/NoPadding");
        desCipher.init(
            (encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE),
            jceKey, iv);
        return desCipher;
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example 24
Source Project: sakai   Source File: BlowFish.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * Decrypt a string using Blowfish
 *
 * @param secret
 *	A hex-encoded secret - secrets longer than the maximum key length will be truncated
 * @param enc	
        *      A hex-encoded ciphertext
 */
public static String decrypt (String secret, String enc) {
	if ( secret == null ) return null;
	if ( secret.length() > MAX_KEY_LENGTH*2 ) {
		secret = secret.substring(0,MAX_KEY_LENGTH*2);
	}
	try {
		byte [] secretBytes = PortableShaUtil.hex2bin(secret);
		SecretKey secretKey = new SecretKeySpec(secretBytes, "Blowfish");
		Cipher dcipher = Cipher.getInstance("Blowfish");
		dcipher.init(Cipher.DECRYPT_MODE, secretKey);
		byte[] dec = PortableShaUtil.hex2bin(enc);
		// Decrypt
		byte[] utf8 = dcipher.doFinal(dec);
		// Decode using utf-8
		return new String(utf8, "UTF8");
	} catch (Exception e) {
		throw new Error(e);
	}
}
 
Example 25
Source Project: xmu-2016-MrCode   Source File: Aes.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static String desEncrypt(String data){
    try
    {
   	 if(data==null||data.equals("")){
   		 return "";
   	 }
   	 data=data.trim();
        byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);
         
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec keyspec = new SecretKeySpec(ZFMPWD.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
         
        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original);
        return originalString.trim();
    }
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 26
Source Project: bcm-android   Source File: MasterSecret.java    License: GNU General Public License v3.0 6 votes vote down vote up
private MasterSecret(Parcel in) {
    byte[] encryptionKeyBytes = new byte[in.readInt()];
    in.readByteArray(encryptionKeyBytes);

    byte[] macKeyBytes = new byte[in.readInt()];
    in.readByteArray(macKeyBytes);

    this.accountContext = (AccountContext) in.readSerializable();
    this.encryptionKey = new SecretKeySpec(encryptionKeyBytes, "AES");
    this.macKey = new SecretKeySpec(macKeyBytes, "HmacSHA1");
    if (null != accountContext) {
        this.tag = Integer.toString(accountContext.hashCode());
    } else {
        this.tag = "unknown";
    }

    // SecretKeySpec does an internal copy in its constructor.
    Arrays.fill(encryptionKeyBytes, (byte) 0x00);
    Arrays.fill(macKeyBytes, (byte) 0x00);
}
 
Example 27
Source Project: Alite   Source File: FileUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
@SuppressLint("TrulyRandom")
public final byte [] encrypt(byte [] toEncrypt, String strKey) {
	byte [] result = toEncrypt;
	if (cipher != null) {
		try {
			SecretKeySpec key = new SecretKeySpec(strKey.getBytes(CHARSET), ENCRYPTION);
			strKey = null;
			cipher.init(Cipher.ENCRYPT_MODE, key);
			result = cipher.doFinal(toEncrypt);
		} catch (Exception e) {
			AliteLog.e("Encrypt", "Error During Encryption", e);
		}
	}
	strKey = null;
	return result;
}
 
Example 28
/**
 * Obtains an initialized DES cipher.
 *
 * @param encryptMode true if encryption is desired, false is decryption
 * is desired.
 * @param key the bytes for the DES key
 * @param ivBytes the initial vector bytes
 */
private final Cipher getInitializedDes(boolean encryptMode, byte[] key,
                                      byte[] ivBytes)
    throws  GSSException  {


    try {
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        SecretKey jceKey = (SecretKey) (new SecretKeySpec(key, "DES"));

        Cipher desCipher = Cipher.getInstance("DES/CBC/NoPadding");
        desCipher.init(
            (encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE),
            jceKey, iv);
        return desCipher;
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example 29
/**
 * Constructor for AESEncryption.
 * This class it to be used for encrypting/decrypting data.
 *
 * @throws Exception if something fails
 */
public AESEncryption(GuildSettings gs) throws Exception {
	String SECRET_KEY_2 = gs.getPrivateKey();
	ivParameterSpec = new IvParameterSpec(SECRET_KEY_1.getBytes(StandardCharsets.UTF_8));
	secretKeySpec = new SecretKeySpec(SECRET_KEY_2.getBytes(StandardCharsets.UTF_8), "AES");
	cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
}
 
Example 30
Source Project: vjtools   Source File: CryptoUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节.
 * 
 * @param input 原始输入字符数组
 * @param key HMAC-SHA1密钥
 */
public static byte[] hmacSha1(byte[] input, byte[] key) {
	try {
		SecretKey secretKey = new SecretKeySpec(key, HMACSHA1_ALG);
		Mac mac = Mac.getInstance(HMACSHA1_ALG);
		mac.init(secretKey);
		return mac.doFinal(input);
	} catch (GeneralSecurityException e) {
		throw ExceptionUtil.unchecked(e);
	}
}