javax.crypto.spec.SecretKeySpec Java Examples
The following examples show how to use
javax.crypto.spec.SecretKeySpec.
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 check out the related API usage on the sidebar.
Example #1
Source File: CipherHelper.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
/** * 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 #2
Source File: CipherUtil.java From snowblossom with Apache License 2.0 | 6 votes |
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 #3
Source File: ExtendedKey.java From bop-bitcoin-client with Apache License 2.0 | 6 votes |
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 #4
Source File: TlsPrfGenerator.java From Bytecoder with Apache License 2.0 | 6 votes |
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 #5
Source File: CipherTest.java From j2objc with Apache License 2.0 | 6 votes |
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 #6
Source File: VotifierProtocol2Decoder.java From NuVotifier with GNU General Public License v3.0 | 6 votes |
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 #7
Source File: WalletUtils.java From blockchain-java with Apache License 2.0 | 6 votes |
/** * 保存钱包数据 */ 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 #8
Source File: Hkdf.java From aws-dynamodb-encryption-java with Apache License 2.0 | 6 votes |
/** * 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 #9
Source File: AesEncryptProvider.java From mPass with Apache License 2.0 | 6 votes |
/** * 构造函数 * * @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 #10
Source File: SecurityServiceImpl.java From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License | 6 votes |
@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 #11
Source File: ShaSaslClient.java From couchbase-jvm-core with Apache License 2.0 | 6 votes |
/** * 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 #12
Source File: AESUtil.java From taoshop with Apache License 2.0 | 6 votes |
/** * 解密 * @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 #13
Source File: TlsRsaPremasterSecretGenerator.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
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 #14
Source File: GXDLMSSecureClient.java From gurux.dlms.java with GNU General Public License v2.0 | 6 votes |
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 #15
Source File: FileUtils.java From Alite with GNU General Public License v3.0 | 6 votes |
@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 #16
Source File: MasterSecret.java From bcm-android with GNU General Public License v3.0 | 6 votes |
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 #17
Source File: Aes.java From xmu-2016-MrCode with GNU General Public License v2.0 | 6 votes |
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 #18
Source File: BlowFish.java From sakai with Educational Community License v2.0 | 6 votes |
/** * 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 #19
Source File: CipherHelper.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** * 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 #20
Source File: CodingUtil.java From xian with Apache License 2.0 | 6 votes |
/** * 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 #21
Source File: SecretKeySpecTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * 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 File: EncryptionUtil.java From tomcat-vault with Apache License 2.0 | 6 votes |
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 #23
Source File: DebugUtil.java From DiscordSRV with GNU General Public License v3.0 | 6 votes |
/** * 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 #24
Source File: EllipticalCurveEncryptor.java From tessera with Apache License 2.0 | 5 votes |
@Override public byte[] sealAfterPrecomputation(byte[] message, Nonce nonce, SharedKey sharedKey) { try { Cipher cipher = Cipher.getInstance(this.symmetricCipher); cipher.init( Cipher.ENCRYPT_MODE, new SecretKeySpec(sharedKey.getKeyBytes(), "AES"), // does this mean that only 16 bytes from the nonce are being used? new GCMParameterSpec(128, nonce.getNonceBytes())); return cipher.doFinal(message); } catch (GeneralSecurityException e) { LOGGER.error("unable to perform symmetric encryption", e); throw new EncryptorException("unable to perform symmetric encryption"); } }
Example #25
Source File: DefaultCipherService.java From deltaspike with Apache License 2.0 | 5 votes |
private SecretKeySpec getSecretKeySpec(String password) { byte[] pwdHash = secureHash(password); byte[] key = Arrays.copyOf(pwdHash, 16); // use only first 128 bit // Note: using 128 bit AES avoids requirement for "Unlimited Crypto" patch return new SecretKeySpec(key, "AES"); }
Example #26
Source File: BulkDataExportUtilTest.java From FHIR with Apache License 2.0 | 5 votes |
@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 #27
Source File: SecurityUtil.java From LockDemo with Apache License 2.0 | 5 votes |
private static SecretKeySpec createKey(String password) { byte[] data = null; if (password == null) { password = ""; } StringBuffer sb = new StringBuffer(32); sb.append(password); while (sb.length() < 32) { sb.append("0"); } if (sb.length() > 32) { sb.setLength(32); } try { data = sb.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return new SecretKeySpec(data, "AES"); }
Example #28
Source File: Sign.java From api-gateway-demo-sign-backend-java with Apache License 2.0 | 5 votes |
/** * 计算HTTP请求签名 * * @param uri 原始HTTP请求PATH(不包含Query) * @param httpMethod 原始HTTP请求方法 * @param headers 原始HTTP请求所有请求头 * @param paramsMap 原始HTTP请求所有Query+Form参数 * @param inputStreamBytes 原始HTTP请求Body体(仅当请求为POST/PUT且非表单请求才需要设置此属性,表单形式的需要将参数放到paramsMap中) * @return 签名结果 * @throws Exception */ public static String serviceSign(String uri, String httpMethod, Map<String, String> headers, Map<String, Object> paramsMap, byte[] inputStreamBytes) throws Exception { Map<String, String> headersToSign = buildHeadersToSign(headers); String bodyMd5 = buildBodyMd5(httpMethod, inputStreamBytes); String resourceToSign = buildResource(uri, paramsMap); String stringToSign = buildStringToSign(headersToSign, resourceToSign, httpMethod, bodyMd5); Mac hmacSha256 = Mac.getInstance(HMAC_SHA256); String secret = signSecretMap.get(headers.get(HTTP_HEADER_TO_LOWER_CASE ? CA_PROXY_SIGN_SECRET_KEY.toLowerCase() : CA_PROXY_SIGN_SECRET_KEY)); byte[] keyBytes = secret.getBytes(ENCODING); hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, HMAC_SHA256)); return new String(Base64.encodeBase64(hmacSha256.doFinal(stringToSign.getBytes(ENCODING))), ENCODING); }
Example #29
Source File: EncryptionUtils.java From java-n-IDE-for-Android with Apache License 2.0 | 5 votes |
/** * Encrypt key (does not use salting, so the encryption result is the same for the same input) * * @param password the secret key to use * @param data the data to encrypt * @return the encrypted data */ static byte[] encryptData(byte[] password, int size, byte[] data) { try { Cipher c = Cipher.getInstance(ENCRYPT_DATA_ALGORITHM); c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(password, SECRET_KEY_ALGORITHM), CBC_SALT_DATA); c.update(new byte[]{(byte)(size >> 24), (byte)(size >> 16), (byte)(size >> 8), (byte)(size)}); return c.doFinal(data); } catch (Exception e) { throw new IllegalStateException(ENCRYPT_DATA_ALGORITHM + " is not available", e); } }
Example #30
Source File: Crypto.java From rtspTortmp with Apache License 2.0 | 5 votes |
/** * Calculates an HMAC SHA256 hash using a default key length. * * * @param input * @param key * @return hmac hashed bytes */ public byte[] calculateHmacSHA256(byte[] input, byte[] key) { byte[] output = null; try { hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); output = hmacSHA256.doFinal(input); } catch (InvalidKeyException e) { L.e("Invalid key", e); } return output; }