org.spongycastle.crypto.InvalidCipherTextException Java Examples
The following examples show how to use
org.spongycastle.crypto.InvalidCipherTextException.
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: ECIESCoder.java From wkcwallet-java with Apache License 2.0 | 6 votes |
public static byte[] decrypt(BigInteger privKey, byte[] cipher, byte[] macData) throws IOException, InvalidCipherTextException { byte[] plaintext; ByteArrayInputStream is = new ByteArrayInputStream(cipher); byte[] ephemBytes = new byte[2*((CURVE.getCurve().getFieldSize()+7)/8) + 1]; is.read(ephemBytes); ECPoint ephem = CURVE.getCurve().decodePoint(ephemBytes); byte[] IV = new byte[KEY_SIZE /8]; is.read(IV); byte[] cipherBody = new byte[is.available()]; is.read(cipherBody); plaintext = decrypt(ephem, privKey, IV, cipherBody, macData); return plaintext; }
Example #2
Source File: SensitiveDataPreApi23.java From android-java-connect-rest-sample with MIT License | 6 votes |
protected byte[] decrypt(byte[] data) { try { SecretKey key = loadKey(); byte[] ivBytes = new byte[16]; // 16 bytes is the IV size for AES256 System.arraycopy(data, 0, ivBytes, 0, ivBytes.length); // Get IV from data byte[] dataWithoutIV = new byte[data.length - ivBytes.length]; // Remove the room made for the IV System.arraycopy(data, ivBytes.length, dataWithoutIV, 0, dataWithoutIV.length); // Then the encrypted data PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())); cipher.init(false, new ParametersWithIV(new KeyParameter(key.getEncoded()), ivBytes)); return cipherData(cipher, dataWithoutIV); } catch(InvalidCipherTextException e) { Log.e(TAG, "Can't decrypt data", e); } return null; }
Example #3
Source File: SensitiveDataPreApi23.java From android-java-connect-rest-sample with MIT License | 6 votes |
protected byte[] encrypt(byte[] data) { // 16 bytes is the IV size for AES256 try { SecretKey key = loadKey(); // Random IV SecureRandom rng = new SecureRandom(); byte[] ivBytes = new byte[16]; // 16 bytes is the IV size for AES256 rng.nextBytes(ivBytes); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())); cipher.init(true, new ParametersWithIV(new KeyParameter(key.getEncoded()), ivBytes)); byte[] encryptedData = cipherData(cipher, data); byte[] encryptedDataWithIV = new byte[encryptedData.length + ivBytes.length]; // Make room for IV System.arraycopy(ivBytes, 0, encryptedDataWithIV, 0, ivBytes.length); // Add IV System.arraycopy(encryptedData, 0, encryptedDataWithIV, ivBytes.length, encryptedData.length); // Then the encrypted data return encryptedDataWithIV; } catch(InvalidCipherTextException e) { Log.e(TAG, "Can't encrypt data", e); } return null; }
Example #4
Source File: Crypto.java From KeePassJava2 with Apache License 2.0 | 6 votes |
/** * Encryption and Decryption Helper * * @param input the candidate for transformation * @param base64in true if base 64 encoded * @param base64out true if we require base 64 out * @param cipher a Cipher initialised for Encrypt or Decrypt * @return the transformed result */ static String CryptoTransform(String input, boolean base64in, boolean base64out, PaddedBufferedBlockCipher cipher) { byte[] bytes; if (base64in) { bytes = Helpers.decodeBase64Content(input.getBytes(), false); } else { bytes = input.getBytes(); } byte[] output = new byte[cipher.getOutputSize(bytes.length)]; int outputlen = cipher.processBytes(bytes, 0, bytes.length, output, 0); try { int len = cipher.doFinal(output, outputlen); // padded buffer is required on bas64 i.e. encrypted direction if (base64out) { return Helpers.encodeBase64Content(output, false); } // trim to buffer length return new String(output, 0, outputlen + len); } catch (InvalidCipherTextException e) { throw new IllegalStateException(e); } }
Example #5
Source File: InsightConnectionService.java From AndroidAPS with GNU Affero General Public License v3.0 | 6 votes |
private void processKeyResponse(KeyResponse keyResponse) { if (state != InsightState.SATL_KEY_REQUEST) { handleException(new ReceivedPacketInInvalidStateException()); return; } try { DerivedKeys derivedKeys = Cryptograph.deriveKeys(Cryptograph.combine(keyRequest.getSatlContent(), keyResponse.getSatlContent()), Cryptograph.decryptRSA(getKeyPair().getPrivateKey(), keyResponse.getPreMasterSecret()), getRandomBytes(), keyResponse.getRandomData()); pairingDataStorage.setCommId(keyResponse.getCommID()); keyRequest = null; randomBytes = null; keyPair = null; verificationString = derivedKeys.getVerificationString(); pairingDataStorage.setOutgoingKey(derivedKeys.getOutgoingKey()); pairingDataStorage.setIncomingKey(derivedKeys.getIncomingKey()); pairingDataStorage.setLastNonceSent(new Nonce()); setState(InsightState.SATL_VERIFY_DISPLAY_REQUEST); sendSatlMessage(new VerifyDisplayRequest()); } catch (InvalidCipherTextException e) { handleException(e); } }
Example #6
Source File: ECIESCoder.java From wkcwallet-java with Apache License 2.0 | 6 votes |
/** * Encryption equivalent to the Crypto++ default ECIES<ECP> settings: * * DL_KeyAgreementAlgorithm: DL_KeyAgreementAlgorithm_DH<struct ECPPoint,struct EnumToType<enum CofactorMultiplicationOption,0> > * DL_KeyDerivationAlgorithm: DL_KeyDerivationAlgorithm_P1363<struct ECPPoint,0,class P1363_KDF2<class SHA1> > * DL_SymmetricEncryptionAlgorithm: DL_EncryptionAlgorithm_Xor<class HMAC<class SHA1>,0> * DL_PrivateKey: DL_Key<ECPPoint> * DL_PrivateKey_EC<class ECP> * * Used for Whisper V3 */ public static byte[] decryptSimple(BigInteger privKey, byte[] cipher) throws IOException, InvalidCipherTextException { EthereumIESEngine iesEngine = new EthereumIESEngine( new ECDHBasicAgreement(), new MGF1BytesGeneratorExt(new SHA1Digest(), 1), new HMac(new SHA1Digest()), new SHA1Digest(), null); IESParameters p = new IESParameters(null, null, KEY_SIZE); ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[0]); iesEngine.setHashMacKey(false); iesEngine.init(new ECPrivateKeyParameters(privKey, CURVE), parametersWithIV, new ECIESPublicKeyParser(ECKey.CURVE)); return iesEngine.processBlock(cipher, 0, cipher.length); }
Example #7
Source File: ECIESCoder.java From wkcwallet-java with Apache License 2.0 | 6 votes |
public static byte[] decrypt(ECPoint ephem, BigInteger prv, byte[] IV, byte[] cipher, byte[] macData) throws InvalidCipherTextException { AESFastEngine aesFastEngine = new AESFastEngine(); EthereumIESEngine iesEngine = new EthereumIESEngine( new ECDHBasicAgreement(), new ConcatKDFBytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()), new SHA256Digest(), new BufferedBlockCipher(new SICBlockCipher(aesFastEngine))); byte[] d = new byte[] {}; byte[] e = new byte[] {}; IESParameters p = new IESWithCipherParameters(d, e, KEY_SIZE, KEY_SIZE); ParametersWithIV parametersWithIV = new ParametersWithIV(p, IV); iesEngine.init(false, new ECPrivateKeyParameters(prv, CURVE), new ECPublicKeyParameters(ephem, CURVE), parametersWithIV); return iesEngine.processBlock(cipher, 0, cipher.length, macData); }
Example #8
Source File: ProfileCipher.java From bcm-android with GNU General Public License v3.0 | 6 votes |
public byte[] encryptName(byte[] input, int paddedLength) { try { byte[] inputPadded = new byte[paddedLength]; if (input.length > inputPadded.length) { throw new IllegalArgumentException("Input is too long: " + new String(input)); } System.arraycopy(input, 0, inputPadded, 0, input.length); byte[] nonce = Util.getSecretBytes(12); GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine()); cipher.init(true, new AEADParameters(new KeyParameter(key), 128, nonce)); byte[] ciphertext = new byte[cipher.getUpdateOutputSize(inputPadded.length)]; cipher.processBytes(inputPadded, 0, inputPadded.length, ciphertext, 0); byte[] tag = new byte[cipher.getOutputSize(0)]; cipher.doFinal(tag, 0); return ByteUtil.combine(nonce, ciphertext, tag); } catch (InvalidCipherTextException e) { throw new AssertionError(e); } }
Example #9
Source File: SecureUtils.java From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static byte[] encryptCCM(@NonNull final byte[] data, @NonNull final byte[] key, @NonNull final byte[] nonce, final int micSize) { final byte[] ccm = new byte[data.length + micSize]; final CCMBlockCipher ccmBlockCipher = new CCMBlockCipher(new AESEngine()); final AEADParameters aeadParameters = new AEADParameters(new KeyParameter(key), micSize * 8, nonce); ccmBlockCipher.init(true, aeadParameters); ccmBlockCipher.processBytes(data, 0, data.length, ccm, data.length); try { ccmBlockCipher.doFinal(ccm, 0); return ccm; } catch (InvalidCipherTextException e) { Log.e(TAG, "Error wile encrypting: " + e.getMessage()); return null; } }
Example #10
Source File: SecureUtils.java From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static byte[] encryptCCM(@NonNull final byte[] data, @NonNull final byte[] key, @NonNull final byte[] nonce, @NonNull final byte[] additionalData, final int micSize) { final byte[] ccm = new byte[data.length + micSize]; final CCMBlockCipher ccmBlockCipher = new CCMBlockCipher(new AESEngine()); final AEADParameters aeadParameters = new AEADParameters(new KeyParameter(key), micSize * 8, nonce, additionalData); ccmBlockCipher.init(true, aeadParameters); ccmBlockCipher.processBytes(data, 0, data.length, ccm, data.length); try { ccmBlockCipher.doFinal(ccm, 0); return ccm; } catch (InvalidCipherTextException e) { Log.e(TAG, "Error wile encrypting: " + e.getMessage()); return null; } }
Example #11
Source File: UpperTransportLayer.java From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Parse upper transport pdu * * @param message access message containing the upper transport pdu */ final void parseUpperTransportPDU(@NonNull final Message message) throws ExtendedInvalidCipherTextException { try { switch (message.getPduType()) { case MeshManagerApi.PDU_TYPE_NETWORK: if (message instanceof AccessMessage) { //Access message final AccessMessage accessMessage = (AccessMessage) message; reassembleLowerTransportAccessPDU(accessMessage); final byte[] decryptedUpperTransportControlPdu = decryptUpperTransportPDU(accessMessage); accessMessage.setAccessPdu(decryptedUpperTransportControlPdu); } else { //TODO //this where control messages such as heartbeat and friendship messages are to be implemented } break; case MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION: final ControlMessage controlMessage = (ControlMessage) message; if (controlMessage.getLowerTransportControlPdu().size() == 1) { final byte[] lowerTransportControlPdu = controlMessage.getLowerTransportControlPdu().get(0); final ByteBuffer buffer = ByteBuffer.wrap(lowerTransportControlPdu) .order(ByteOrder.BIG_ENDIAN); message.setOpCode(buffer.get()); final byte[] parameters = new byte[buffer.capacity() - 1]; buffer.get(parameters); message.setParameters(parameters); } break; } } catch (InvalidCipherTextException ex) { throw new ExtendedInvalidCipherTextException(ex.getMessage(), ex.getCause(), TAG); } }
Example #12
Source File: ProfileCipher.java From bcm-android with GNU General Public License v3.0 | 5 votes |
public byte[] decryptName(byte[] input) throws InvalidCiphertextException { try { if (input.length < 12 + 16 + 1) { throw new InvalidCiphertextException("Too short: " + input.length); } byte[] nonce = new byte[12]; System.arraycopy(input, 0, nonce, 0, nonce.length); GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine()); cipher.init(false, new AEADParameters(new KeyParameter(key), 128, nonce)); byte[] paddedPlaintextOne = new byte[cipher.getUpdateOutputSize(input.length - 12)]; cipher.processBytes(input, 12, input.length - 12, paddedPlaintextOne, 0); byte[] paddedPlaintextTwo = new byte[cipher.getOutputSize(0)]; cipher.doFinal(paddedPlaintextTwo, 0); byte[] paddedPlaintext = ByteUtil.combine(paddedPlaintextOne, paddedPlaintextTwo); int plaintextLength = 0; for (int i = paddedPlaintext.length - 1; i >= 0; i--) { if (paddedPlaintext[i] != (byte) 0x00) { plaintextLength = i + 1; break; } } byte[] plaintext = new byte[plaintextLength]; System.arraycopy(paddedPlaintext, 0, plaintext, 0, plaintextLength); return plaintext; } catch (InvalidCipherTextException e) { throw new InvalidCiphertextException(e); } }
Example #13
Source File: ProfileCipherOutputStream.java From bcm-android with GNU General Public License v3.0 | 5 votes |
@Override public void flush() throws IOException { try { byte[] output = new byte[cipher.getOutputSize(0)]; int encrypted = cipher.doFinal(output, 0); super.write(output, 0, encrypted); super.flush(); } catch (InvalidCipherTextException e) { throw new AssertionError(e); } }
Example #14
Source File: SensitiveDataPreApi23.java From android-java-connect-rest-sample with MIT License | 5 votes |
private byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data) throws InvalidCipherTextException { int minSize = cipher.getOutputSize(data.length); byte[] outBuf = new byte[minSize]; int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0); int length2 = cipher.doFinal(outBuf, length1); int actualLength = length1 + length2; byte[] result = new byte[actualLength]; System.arraycopy(outBuf, 0, result, 0, result.length); return result; }
Example #15
Source File: ECIESCoder.java From wkcwallet-java with Apache License 2.0 | 5 votes |
/** * Encryption equivalent to the Crypto++ default ECIES<ECP> settings: * * DL_KeyAgreementAlgorithm: DL_KeyAgreementAlgorithm_DH<struct ECPPoint,struct EnumToType<enum CofactorMultiplicationOption,0> > * DL_KeyDerivationAlgorithm: DL_KeyDerivationAlgorithm_P1363<struct ECPPoint,0,class P1363_KDF2<class SHA1> > * DL_SymmetricEncryptionAlgorithm: DL_EncryptionAlgorithm_Xor<class HMAC<class SHA1>,0> * DL_PrivateKey: DL_Key<ECPPoint> * DL_PrivateKey_EC<class ECP> * * Used for Whisper V3 */ public static byte[] encryptSimple(ECPoint pub, byte[] plaintext) throws IOException, InvalidCipherTextException { EthereumIESEngine iesEngine = new EthereumIESEngine( new ECDHBasicAgreement(), new MGF1BytesGeneratorExt(new SHA1Digest(), 1), new HMac(new SHA1Digest()), new SHA1Digest(), null); IESParameters p = new IESParameters(null, null, KEY_SIZE); ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[0]); iesEngine.setHashMacKey(false); ECKeyPairGenerator eGen = new ECKeyPairGenerator(); SecureRandom random = new SecureRandom(); KeyGenerationParameters gParam = new ECKeyGenerationParameters(CURVE, random); eGen.init(gParam); // AsymmetricCipherKeyPairGenerator testGen = new AsymmetricCipherKeyPairGenerator() { // ECKey priv = ECKey.fromPrivate(Hex.decode("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a")); // // @Override // public void init(KeyGenerationParameters keyGenerationParameters) { // } // // @Override // public AsymmetricCipherKeyPair generateKeyPair() { // return new AsymmetricCipherKeyPair(new ECPublicKeyParameters(priv.getPubKeyPoint(), CURVE), // new ECPrivateKeyParameters(priv.getPrivKey(), CURVE)); // } // }; EphemeralKeyPairGenerator ephemeralKeyPairGenerator = new EphemeralKeyPairGenerator(/*testGen*/eGen, new ECIESPublicKeyEncoder()); iesEngine.init(new ECPublicKeyParameters(pub, CURVE), parametersWithIV, ephemeralKeyPairGenerator); return iesEngine.processBlock(plaintext, 0, plaintext.length); }
Example #16
Source File: SecureUtils.java From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static byte[] decryptCCM(@NonNull final byte[] data, @NonNull final byte[] key, @NonNull final byte[] nonce, final int micSize) throws InvalidCipherTextException { final byte[] ccm = new byte[data.length - micSize]; final CCMBlockCipher ccmBlockCipher = new CCMBlockCipher(new AESEngine()); final AEADParameters aeadParameters = new AEADParameters(new KeyParameter(key), micSize * 8, nonce); ccmBlockCipher.init(false, aeadParameters); ccmBlockCipher.processBytes(data, 0, data.length, ccm, 0); ccmBlockCipher.doFinal(ccm, 0); return ccm; }
Example #17
Source File: SecureUtils.java From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static byte[] decryptCCM(@NonNull final byte[] data, @NonNull final byte[] key, @NonNull final byte[] nonce, @NonNull final byte[] additionalData, final int micSize) throws InvalidCipherTextException { final byte[] ccm = new byte[data.length - micSize]; final CCMBlockCipher ccmBlockCipher = new CCMBlockCipher(new AESEngine()); final AEADParameters aeadParameters = new AEADParameters(new KeyParameter(key), micSize * 8, nonce, additionalData); ccmBlockCipher.init(false, aeadParameters); ccmBlockCipher.processBytes(data, 0, data.length, ccm, 0); ccmBlockCipher.doFinal(ccm, 0); return ccm; }
Example #18
Source File: Cryptograph.java From SightRemote with GNU General Public License v3.0 | 4 votes |
private static byte[] processRSA(AsymmetricKeyParameter key, byte[] data, boolean encrypt) throws InvalidCipherTextException { OAEPEncoding cipher = new OAEPEncoding(new RSAEngine()); cipher.init(encrypt, key); return cipher.processBlock(data, 0, data.length); }
Example #19
Source File: Cryptograph.java From SightRemote with GNU General Public License v3.0 | 4 votes |
public static byte[] decryptRSA(RSAPrivateCrtKeyParameters key, byte[] data) throws InvalidCipherTextException { return processRSA(key, data, false); }
Example #20
Source File: Cryptograph.java From AndroidAPS with GNU Affero General Public License v3.0 | 4 votes |
private static byte[] processRSA(AsymmetricKeyParameter key, byte[] data, boolean encrypt) throws InvalidCipherTextException { OAEPEncoding cipher = new OAEPEncoding(new RSAEngine()); cipher.init(encrypt, key); return cipher.processBlock(data, 0, data.length); }
Example #21
Source File: Cryptograph.java From AndroidAPS with GNU Affero General Public License v3.0 | 4 votes |
public static byte[] decryptRSA(RSAPrivateCrtKeyParameters key, byte[] data) throws InvalidCipherTextException { return processRSA(key, data, false); }
Example #22
Source File: BaseMeshMessageHandler.java From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Parse the mesh network/proxy pdus * <p> * This method will try to network layer de-obfuscation and decryption using the available network keys * </p> * * @param pdu mesh pdu that was sent * @param network {@link MeshNetwork} */ protected void parseMeshPduNotifications(@NonNull final byte[] pdu, @NonNull final MeshNetwork network) throws ExtendedInvalidCipherTextException { final List<NetworkKey> networkKeys = network.getNetKeys(); final int ivi = ((pdu[1] & 0xFF) >>> 7) & 0x01; final int nid = pdu[1] & 0x7F; final int acceptedIvIndex = network.getIvIndex().getIvIndex(); int ivIndex = acceptedIvIndex == 0 ? 0 : acceptedIvIndex - 1; while (ivIndex <= ivIndex + 1) { //Here we go through all the network keys and filter out network keys based on the nid. for (int i = 0; i < networkKeys.size(); i++) { NetworkKey networkKey = networkKeys.get(i); final SecureUtils.K2Output k2Output = SecureUtils.calculateK2(networkKey.getKey(), SecureUtils.K2_MASTER_INPUT); if (nid == k2Output.getNid()) { final byte[] networkHeader = deObfuscateNetworkHeader(pdu, MeshParserUtils.intToBytes(ivIndex), k2Output.getPrivacyKey()); final int ctlTtl = networkHeader[0]; final int ctl = (ctlTtl >> 7) & 0x01; final int ttl = ctlTtl & 0x7F; Log.v(TAG, "TTL for received message: " + ttl); final int src = MeshParserUtils.unsignedBytesToInt(networkHeader[5], networkHeader[4]); final ProvisionedMeshNode node = network.getNode(src); if (node == null) { continue; } final byte[] sequenceNumber = ByteBuffer.allocate(3).order(ByteOrder.BIG_ENDIAN).put(networkHeader, 1, 3).array(); Log.v(TAG, "Sequence number of received access message: " + MeshParserUtils.getSequenceNumber(sequenceNumber)); //TODO validate ivi byte[] nonce; try { final int networkPayloadLength = pdu.length - (2 + networkHeader.length); final byte[] transportPdu = new byte[networkPayloadLength]; System.arraycopy(pdu, 8, transportPdu, 0, networkPayloadLength); final byte[] decryptedPayload; final MeshMessageState state; if (pdu[0] == MeshManagerApi.PDU_TYPE_NETWORK) { nonce = createNetworkNonce((byte) ctlTtl, sequenceNumber, src, MeshParserUtils.intToBytes(ivIndex)); decryptedPayload = SecureUtils.decryptCCM(transportPdu, k2Output.getEncryptionKey(), nonce, SecureUtils.getNetMicLength(ctl)); state = getState(src); } else { nonce = createProxyNonce(sequenceNumber, src, MeshParserUtils.intToBytes(ivIndex)); decryptedPayload = SecureUtils.decryptCCM(transportPdu, k2Output.getEncryptionKey(), nonce, SecureUtils.getNetMicLength(ctl)); state = getState(MeshAddress.UNASSIGNED_ADDRESS); } if (state != null) { //TODO look in to proxy filter messages ((DefaultNoOperationMessageState) state).parseMeshPdu(node, pdu, networkHeader, decryptedPayload, ivIndex, sequenceNumber); return; } } catch (InvalidCipherTextException ex) { if (i == networkKeys.size() - 1) { throw new ExtendedInvalidCipherTextException(ex.getMessage(), ex.getCause(), TAG); } } } } ivIndex++; } }
Example #23
Source File: ECIESCoder.java From wkcwallet-java with Apache License 2.0 | 4 votes |
public static byte[] decrypt(BigInteger privKey, byte[] cipher) throws IOException, InvalidCipherTextException { return decrypt(privKey, cipher, null); }
Example #24
Source File: UpperTransportLayer.java From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Returns the decrypted upper transport pdu * * @param accessMessage Access message object containing the upper transport pdu */ private byte[] decryptUpperTransportPDU(@NonNull final AccessMessage accessMessage) throws InvalidCipherTextException { byte[] decryptedUpperTransportPDU; final byte[] key; //Check if the key used for encryption is an application key or a device key final byte[] nonce; if (APPLICATION_KEY_IDENTIFIER == accessMessage.getAkf()) { key = mMeshNode.getDeviceKey(); //If its a device key that was used to encrypt the message we need to create a device nonce to decrypt it nonce = createDeviceNonce(accessMessage.getAszmic(), accessMessage.getSequenceNumber(), accessMessage.getSrc(), accessMessage.getDst(), accessMessage.getIvIndex()); } else { key = mUpperTransportLayerCallbacks.getApplicationKey(accessMessage.getAid()); if (key == null) throw new IllegalArgumentException("Unable to find the app key to decrypt the message"); final int aid = SecureUtils.calculateK4(key); if (aid != accessMessage.getAid()) { throw new IllegalArgumentException("Unable to decrypt the message, invalid application key identifier"); } //If its an application key that was used to encrypt the message we need to create a application nonce to decrypt it nonce = createApplicationNonce(accessMessage.getAszmic(), accessMessage.getSequenceNumber(), accessMessage.getSrc(), accessMessage.getDst(), accessMessage.getIvIndex()); } final int transportMicLength = accessMessage.getAszmic() == SZMIC ? MAXIMUM_TRANSMIC_LENGTH : MINIMUM_TRANSMIC_LENGTH; if (MeshAddress.isValidVirtualAddress(accessMessage.getDst())) { final UUID label = mUpperTransportLayerCallbacks.getLabel(accessMessage.getDst()); if (label != null) { decryptedUpperTransportPDU = SecureUtils .decryptCCM(accessMessage.getUpperTransportPdu(), key, nonce, MeshParserUtils.uuidToBytes(label), transportMicLength); } else { throw new ExtendedInvalidCipherTextException("Label UUID unknown", null, TAG); } } else { decryptedUpperTransportPDU = SecureUtils.decryptCCM(accessMessage.getUpperTransportPdu(), key, nonce, transportMicLength); } final byte[] tempBytes = new byte[decryptedUpperTransportPDU.length]; ByteBuffer decryptedBuffer = ByteBuffer.wrap(tempBytes); decryptedBuffer.order(ByteOrder.LITTLE_ENDIAN); decryptedBuffer.put(decryptedUpperTransportPDU); decryptedUpperTransportPDU = decryptedBuffer.array(); return decryptedUpperTransportPDU; }
Example #25
Source File: NetworkLayer.java From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Parses control message * * @param provisionerAddress Provisioner address. * @param data Data received from the node. * @param networkHeader De-obfuscated network header. * @param decryptedNetworkPayload Decrypted network payload. * @param src Source address where the pdu originated from. * @param sequenceNumber Sequence number of the received message. * @param ivIndex IV Index used for decryption. * @return a complete {@link ControlMessage} or null if the message was unable to parsed */ private ControlMessage parseControlMessage(@Nullable final Integer provisionerAddress, @NonNull final byte[] data, @NonNull final byte[] networkHeader, @NonNull final byte[] decryptedNetworkPayload, final int src, @NonNull final byte[] sequenceNumber, int ivIndex) throws ExtendedInvalidCipherTextException { try { final int ttl = networkHeader[0] & 0x7F; final int dst = MeshParserUtils.unsignedBytesToInt(decryptedNetworkPayload[1], decryptedNetworkPayload[0]); //Removing the mDst here final byte[] decryptedProxyPdu = ByteBuffer.allocate(2 + networkHeader.length + decryptedNetworkPayload.length) .order(ByteOrder.BIG_ENDIAN) .put(data, 0, 2) .put(networkHeader) .put(decryptedNetworkPayload) .array(); //We check the pdu type final int pduType = data[0]; switch (pduType) { case MeshManagerApi.PDU_TYPE_NETWORK: //This is not possible however let's return null if (provisionerAddress == null) { return null; } //Check if the message is directed to us, if its not ignore the message if (provisionerAddress != dst) { Log.v(TAG, "Received a control message that was not directed to us, so we drop it"); return null; } if (isSegmentedMessage(decryptedNetworkPayload[2])) { return parseSegmentedControlMessage(data, decryptedProxyPdu, ttl, src, dst); } else { return parseUnsegmentedControlMessage(data, decryptedProxyPdu, ttl, src, dst, sequenceNumber); } case MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION: //Proxy configuration messages are segmented only at the gatt level return parseUnsegmentedControlMessage(data, decryptedProxyPdu, ttl, src, dst, sequenceNumber); default: return null; } } catch (InvalidCipherTextException ex) { throw new ExtendedInvalidCipherTextException(ex.getMessage(), ex.getCause(), TAG); } }