List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec
public IvParameterSpec(byte[] iv, int offset, int len)
len
bytes in iv
, beginning at offset
inclusive, as the IV. From source file:mobisocial.musubi.nearby.scanner.GpsScannerTask.java
@Override protected List<NearbyItem> doInBackground(Void... params) { if (DBG)//from w w w .ja va 2 s.c o m Log.d(TAG, "Scanning for nearby gps..."); while (!mmLocationScanComplete) { synchronized (mmLocationResult) { if (!mmLocationScanComplete) { try { if (DBG) Log.d(TAG, "Waiting for location results..."); mmLocationResult.wait(); } catch (InterruptedException e) { } } } } if (DBG) Log.d(TAG, "Got location " + mmLocation); if (isCancelled()) { return null; } try { if (DBG) Log.d(TAG, "Querying gps server..."); Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/findgroup"); StringBuffer sb = new StringBuffer(); DefaultHttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(uri.toString()); httpPost.addHeader("Content-Type", "application/json"); JSONArray buckets = new JSONArray(); double lat = mmLocation.getLatitude(); double lng = mmLocation.getLongitude(); long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2); Log.i(TAG, "coords: " + Arrays.toString(coords)); //TODO: encrypt coords with mmPassword for (long c : coords) { MessageDigest md; try { byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes(); md = MessageDigest.getInstance("SHA-256"); ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length); b.putLong(c); b.put(obfuscate); String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT); buckets.put(buckets.length(), secret_bucket); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("your platform does not support sha256", e); } } Log.i(TAG, "buckets: " + buckets); httpPost.setEntity(new StringEntity(buckets.toString())); try { HttpResponse execute = client.execute(httpPost); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { if (isCancelled()) { return null; } sb.append(s); } } catch (Exception e) { e.printStackTrace(); } HashSet<Pair<TByteArrayList, TByteArrayList>> dupes = new HashSet<Pair<TByteArrayList, TByteArrayList>>(); String response = sb.toString(); JSONArray groupsJSON = new JSONArray(response); Log.d(TAG, "Got " + groupsJSON.length() + " groups"); for (int i = 0; i < groupsJSON.length(); i++) { try { String s_enc_data = groupsJSON.get(i).toString(); byte[] enc_data = Base64.decode(s_enc_data, Base64.DEFAULT); byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes()); byte[] data; Cipher cipher; AlgorithmParameterSpec iv_spec; SecretKeySpec sks; try { cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); } catch (Exception e) { throw new RuntimeException("AES not supported on this platform", e); } try { iv_spec = new IvParameterSpec(enc_data, 0, 16); sks = new SecretKeySpec(key, "AES"); cipher.init(Cipher.DECRYPT_MODE, sks, iv_spec); } catch (Exception e) { throw new RuntimeException("bad iv or key", e); } try { data = cipher.doFinal(enc_data, 16, enc_data.length - 16); } catch (Exception e) { throw new RuntimeException("body decryption failed", e); } JSONObject group = new JSONObject(new String(data)); String group_name = group.getString("group_name"); byte[] group_capability = Base64.decode(group.getString("group_capability"), Base64.DEFAULT); String sharer_name = group.getString("sharer_name"); byte[] sharer_hash = Base64.decode(group.getString("sharer_hash"), Base64.DEFAULT); byte[] thumbnail = null; if (group.has("thumbnail")) thumbnail = Base64.decode(group.getString("thumbnail"), Base64.DEFAULT); int member_count = group.getInt("member_count"); int sharer_type = group.getInt("sharer_type"); Pair<TByteArrayList, TByteArrayList> p = Pair.with(new TByteArrayList(sharer_hash), new TByteArrayList(group_capability)); if (dupes.contains(p)) continue; dupes.add(p); addNearbyItem(new NearbyFeed(mContext, group_name, group_capability, sharer_name, Authority.values()[sharer_type], sharer_hash, thumbnail, member_count)); } catch (Throwable e) { Log.e(TAG, "Failed to parse group " + i, e); } } } catch (Exception e) { if (DBG) Log.d(TAG, "Error searching nearby feeds", e); } return null; }
From source file:com.vmware.o11n.plugin.crypto.service.CryptoEncryptionService.java
/** * TripleDES (EDE) Decryption CBC Mode with PKCS5 padding * * @param encryptedB64 Encrypted data Base64 encoded * @param secretB64 Encryption secret Base64 encoded. Secret must be at least 24 bytes. Only the first 24 bytes will be used. * @param ivB64 Initialization Vector Base64 encoded. Only first 8 bytes will be used. * @return Original data Base64 encoded. * @throws NoSuchAlgorithmException//from w w w. ja v a 2 s .c om * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws IOException * @throws BadPaddingException * @throws IllegalBlockSizeException */ public String tripleDesDecrypt(String encryptedB64, String secretB64, String ivB64) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String dataB64 = null; final byte[] encryptedBytes = Base64.decodeBase64(encryptedB64); final byte[] secretBytes = Base64.decodeBase64(secretB64); final byte[] ivBytes = Base64.decodeBase64(ivB64); final Cipher cipher = Cipher.getInstance(DESEDE_CIPHER); DESedeKeySpec keySpec = new DESedeKeySpec(secretBytes); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keySpec.getKey(), "DESede"), new IvParameterSpec(ivBytes, 0, cipher.getBlockSize())); dataB64 = Base64.encodeBase64String(cipher.doFinal(encryptedBytes)); return dataB64; }
From source file:net.ymate.platform.module.wechat.support.MessageHelper.java
static String encrypt(String appId, byte[] aesKey, String randomStr, String messageStr) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(__CHARSET); byte[] textBytes = messageStr.getBytes(__CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(__CHARSET); // randomStr + networkBytesOrder + text + appid byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes);/*from w ww .ja v a 2s . co m*/ byteCollector.addBytes(appidBytes); // ... + pad: ?? byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); // ?, byte[] unencrypted = byteCollector.toBytes(); try { // ?AESCBC? Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); // byte[] encrypted = cipher.doFinal(unencrypted); // BASE64?? String base64Encrypted = Base64.encodeBase64URLSafeString(encrypted); // return base64Encrypted; } catch (Exception e) { throw new AesException(AesException.EncryptAESError, RuntimeUtils.unwrapThrow(e)); } }
From source file:com.wallellen.wechat.common.util.crypto.WxCryptUtil.java
/** * .//from w ww . j a v a 2 s .c om * * @param plainText ? * @return ?base64? */ protected String encrypt(String randomStr, String plainText) { ByteGroup byteCollector = new ByteGroup(); byte[] randomStringBytes = randomStr.getBytes(CHARSET); byte[] plainTextBytes = plainText.getBytes(CHARSET); byte[] bytesOfSizeInNetworkOrder = number2BytesInNetworkOrder(plainTextBytes.length); byte[] appIdBytes = appidOrCorpid.getBytes(CHARSET); // randomStr + networkBytesOrder + text + appid byteCollector.addBytes(randomStringBytes); byteCollector.addBytes(bytesOfSizeInNetworkOrder); byteCollector.addBytes(plainTextBytes); byteCollector.addBytes(appIdBytes); // ... + pad: ?? byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); // ?, byte[] unencrypted = byteCollector.toBytes(); try { // ?AESCBC? Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); // byte[] encrypted = cipher.doFinal(unencrypted); // BASE64?? return base64.encodeToString(encrypted); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:de.hybris.platform.cuppytrail.impl.DefaultSecureTokenService.java
private byte[] decrypt(final String encryptedText, final byte[] encryptionKeyBytes) throws GeneralSecurityException { // Decode base64 encoded string final byte[] encryptedBytes = Base64.decodeBase64(encryptedText.getBytes()); if (encryptedBytes == null || encryptedBytes.length < AESIV_LENGTH) { throw new IllegalArgumentException("Encrypted data too short"); }//w w w .j a v a2s . co m // Create the cypher final Cipher cipher = Cipher.getInstance(ENCRYPTION_CIPHER); // The IV is the first 16 bytes of the data final IvParameterSpec ivSpec = new IvParameterSpec(encryptedBytes, 0, AESIV_LENGTH); cipher.init(Cipher.DECRYPT_MODE, buildSecretKey(encryptionKeyBytes), ivSpec); return cipher.doFinal(encryptedBytes, AESIV_LENGTH, encryptedBytes.length - AESIV_LENGTH); }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
private Cipher getEncryptCipher(String dhSKAlgo, PublicKey publicKey) throws Exception { try {/*from ww w . j a va 2 s .co m*/ if (_encrypt == null) { KeyAgreement ka = KeyAgreement.getInstance("DH"); ka.init(dhPrivateKey); ka.doPhase(publicKey, true); Cipher encrypt; int keysize = getKeySize(dhSKAlgo); int blocksize = getBlockSize(dhSKAlgo); if (keysize == -1 || blocksize == -1) { SecretKey sKey = ka.generateSecret(dhSKAlgo); encrypt = Cipher.getInstance(dhSKAlgo); encrypt.init(Cipher.ENCRYPT_MODE, sKey); } else { String dhAlgoStr = getDhAlgoStr(dhSKAlgo); byte[] sKeyBytes = ka.generateSecret(); SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, dhAlgoStr); IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize); encrypt = Cipher.getInstance(dhAlgoStr + "/CBC/PKCS5Padding"); encrypt.init(Cipher.ENCRYPT_MODE, sks, ivps); } _encrypt = encrypt; } } catch (Exception ex) { throw ex; } return _encrypt; }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
private Cipher getDecryptCipher(String dhSKAlgo, PublicKey publicKey) throws Exception { if (_decrypt == null) { try {/*from ww w . ja v a2 s . c o m*/ KeyAgreement ka = KeyAgreement.getInstance("DH"); ka.init(dhPrivateKey); ka.doPhase(publicKey, true); Cipher decrypt; int keysize = getKeySize(dhSKAlgo); int blocksize = getBlockSize(dhSKAlgo); if (keysize == -1 || blocksize == -1) { SecretKey sKey = ka.generateSecret(dhSKAlgo); decrypt = Cipher.getInstance(dhSKAlgo); decrypt.init(Cipher.DECRYPT_MODE, sKey); } else { String algoStr = getDhAlgoStr(dhSKAlgo); byte[] sKeyBytes = ka.generateSecret(); SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr); IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize); decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding"); decrypt.init(Cipher.DECRYPT_MODE, sks, ivps); } _decrypt = decrypt; } catch (Exception ex) { throw ex; } } return _decrypt; }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
public static Properties readCredentials(DataInputStream dis, DataOutputStream dos, DistributedSystem system, SecurityService securityService) throws GemFireSecurityException, IOException { boolean requireAuthentication = securityService.isClientSecurityRequired(); Properties credentials = null; try {//from w w w. j ava 2s. c o m byte secureMode = dis.readByte(); throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE); if (secureMode == CREDENTIALS_NORMAL) { if (requireAuthentication) { credentials = DataSerializer.readProperties(dis); } else { DataSerializer.readProperties(dis); // ignore the credentials } } else if (secureMode == CREDENTIALS_DHENCRYPT) { boolean sendAuthentication = dis.readBoolean(); InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter(); // Get the symmetric encryption algorithm to be used String skAlgo = DataSerializer.readString(dis); // Get the public key of the other side byte[] keyBytes = DataSerializer.readByteArray(dis); byte[] challenge = null; PublicKey pubKey = null; if (requireAuthentication) { // Generate PublicKey from encoded form X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); pubKey = keyFact.generatePublic(x509KeySpec); // Send the public key to other side keyBytes = dhPublicKey.getEncoded(); challenge = new byte[64]; random.nextBytes(challenge); // If the server has to also authenticate itself then // sign the challenge from client. if (sendAuthentication) { // Get the challenge string from client byte[] clientChallenge = DataSerializer.readByteArray(dis); if (privateKeyEncrypt == null) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE .toLocalizedString()); } // Sign the challenge from client and send it to the client Signature sig = Signature.getInstance(privateKeySignAlgo); sig.initSign(privateKeyEncrypt); sig.update(clientChallenge); byte[] signedBytes = sig.sign(); dos.writeByte(REPLY_OK); DataSerializer.writeByteArray(keyBytes, dos); // DataSerializer.writeString(privateKeyAlias, dos); DataSerializer.writeString(privateKeySubject, dos); DataSerializer.writeByteArray(signedBytes, dos); securityLogWriter.fine("HandShake: sent the signed client challenge"); } else { // These two lines should not be moved before the if{} statement in // a common block for both if...then...else parts. This is to handle // the case when an AuthenticationFailedException is thrown by the // if...then part when sending the signature. dos.writeByte(REPLY_OK); DataSerializer.writeByteArray(keyBytes, dos); } // Now send the server challenge DataSerializer.writeByteArray(challenge, dos); securityLogWriter.fine("HandShake: sent the public key and challenge"); dos.flush(); // Read and decrypt the credentials byte[] encBytes = DataSerializer.readByteArray(dis); KeyAgreement ka = KeyAgreement.getInstance("DH"); ka.init(dhPrivateKey); ka.doPhase(pubKey, true); Cipher decrypt; int keysize = getKeySize(skAlgo); int blocksize = getBlockSize(skAlgo); if (keysize == -1 || blocksize == -1) { SecretKey sKey = ka.generateSecret(skAlgo); decrypt = Cipher.getInstance(skAlgo); decrypt.init(Cipher.DECRYPT_MODE, sKey); } else { String algoStr = getDhAlgoStr(skAlgo); byte[] sKeyBytes = ka.generateSecret(); SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr); IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize); decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding"); decrypt.init(Cipher.DECRYPT_MODE, sks, ivps); } byte[] credentialBytes = decrypt.doFinal(encBytes); ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes); DataInputStream dinp = new DataInputStream(bis); credentials = DataSerializer.readProperties(dinp); byte[] challengeRes = DataSerializer.readByteArray(dinp); // Check the challenge string if (!Arrays.equals(challenge, challengeRes)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT .toLocalizedString()); } dinp.close(); } else { if (sendAuthentication) { // Read and ignore the client challenge DataSerializer.readByteArray(dis); } dos.writeByte(REPLY_AUTH_NOT_REQUIRED); dos.flush(); } } else if (secureMode == SECURITY_MULTIUSER_NOTIFICATIONCHANNEL) { // hitesh there will be no credential CCP will get credential(Principal) using // ServerConnection.. logger.debug("readCredential where multiuser mode creating callback connection"); } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex); } return credentials; }