java.security.spec.InvalidParameterSpecException#javax.crypto.spec.SecretKeySpec源码实例Demo

下面列出了java.security.spec.InvalidParameterSpecException#javax.crypto.spec.SecretKeySpec 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Bytecoder   文件: TlsPrfGenerator.java
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);
    }
}
 
源代码2 项目: FHIR   文件: BulkDataExportUtilTest.java
@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);
}
 
源代码3 项目: t-io   文件: ACEUtils.java
/**
 * 加密
 * @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次加密的作用。
}
 
源代码4 项目: burp-api-drops   文件: AES.java
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);
}
 
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;
        }
    }
 
源代码6 项目: TelePlus-Android   文件: CachedContentIndex.java
/**
 * 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));
}
 
源代码7 项目: bop-bitcoin-client   文件: ExtendedKey.java
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);
	}
}
 
源代码8 项目: snowblossom   文件: CipherUtil.java
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);
  }

}
 
源代码9 项目: j2objc   文件: CipherTest.java
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());
    }
}
 
源代码10 项目: NuVotifier   文件: VotifierProtocol2Decoder.java
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);
}
 
源代码11 项目: blockchain-java   文件: WalletUtils.java
/**
 * 保存钱包数据
 */
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 !");
    }
}
 
源代码12 项目: aws-dynamodb-encryption-java   文件: Hkdf.java
/**
 * 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
    }
}
 
源代码13 项目: mPass   文件: AesEncryptProvider.java
/**
 * 构造函数
 *
 * @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));
}
 
@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();
}
 
源代码15 项目: gurux.dlms.java   文件: GXDLMSSecureClient.java
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;
}
 
源代码16 项目: couchbase-jvm-core   文件: ShaSaslClient.java
/**
 * 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);
    }
}
 
源代码17 项目: taoshop   文件: AESUtil.java
/**
 * 解密
 * @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);
}
 
源代码18 项目: DiscordSRV   文件: DebugUtil.java
/**
 * 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;
    }
}
 
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");
}
 
源代码20 项目: tomcat-vault   文件: EncryptionUtil.java
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;
}
 
源代码21 项目: j2objc   文件: SecretKeySpecTest.java
/**
 * 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);
}
 
源代码22 项目: xian   文件: CodingUtil.java
/**
 * 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;
}
 
源代码23 项目: openjdk-jdk8u-backup   文件: CipherHelper.java
/**
 * 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;
    }
}
 
源代码24 项目: sakai   文件: BlowFish.java
/**
 * 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);
	}
}
 
源代码25 项目: xmu-2016-MrCode   文件: Aes.java
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;
    }
}
 
源代码26 项目: bcm-android   文件: MasterSecret.java
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);
}
 
源代码27 项目: Alite   文件: FileUtils.java
@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;
}
 
源代码28 项目: openjdk-8-source   文件: CipherHelper.java
/**
 * 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;
    }
}
 
源代码29 项目: DisCal-Discord-Bot   文件: AESEncryption.java
/**
 * 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");
}
 
源代码30 项目: vjtools   文件: CryptoUtil.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_ALG);
		Mac mac = Mac.getInstance(HMACSHA1_ALG);
		mac.init(secretKey);
		return mac.doFinal(input);
	} catch (GeneralSecurityException e) {
		throw ExceptionUtil.unchecked(e);
	}
}