Example usage for java.math BigInteger toByteArray

List of usage examples for java.math BigInteger toByteArray

Introduction

In this page you can find the example usage for java.math BigInteger toByteArray.

Prototype

public byte[] toByteArray() 

Source Link

Document

Returns a byte array containing the two's-complement representation of this BigInteger.

Usage

From source file:org.apache.hadoop.hbase.util.Bytes.java

/**
 * Iterate over keys within the passed range.
 *//* w  ww  . ja  v a  2 s .  c o  m*/
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive,
        final int num) {
    byte[] aPadded;
    byte[] bPadded;
    if (a.length < b.length) {
        aPadded = padTail(a, b.length - a.length);
        bPadded = b;
    } else if (b.length < a.length) {
        aPadded = a;
        bPadded = padTail(b, a.length - b.length);
    } else {
        aPadded = a;
        bPadded = b;
    }
    if (compareTo(aPadded, bPadded) >= 0) {
        throw new IllegalArgumentException("b <= a");
    }
    if (num <= 0) {
        throw new IllegalArgumentException("num cannot be <= 0");
    }
    byte[] prependHeader = { 1, 0 };
    final BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
    final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
    BigInteger diffBI = stopBI.subtract(startBI);
    if (inclusive) {
        diffBI = diffBI.add(BigInteger.ONE);
    }
    final BigInteger splitsBI = BigInteger.valueOf(num + 1);
    if (diffBI.compareTo(splitsBI) < 0) {
        return null;
    }
    final BigInteger intervalBI;
    try {
        intervalBI = diffBI.divide(splitsBI);
    } catch (Exception e) {
        LOG.error("Exception caught during division", e);
        return null;
    }

    final Iterator<byte[]> iterator = new Iterator<byte[]>() {
        private int i = -1;

        @Override
        public boolean hasNext() {
            return i < num + 1;
        }

        @Override
        public byte[] next() {
            i++;
            if (i == 0)
                return a;
            if (i == num + 1)
                return b;

            BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i)));
            byte[] padded = curBI.toByteArray();
            if (padded[1] == 0)
                padded = tail(padded, padded.length - 2);
            else
                padded = tail(padded, padded.length - 1);
            return padded;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }

    };

    return new Iterable<byte[]>() {
        @Override
        public Iterator<byte[]> iterator() {
            return iterator;
        }
    };
}

From source file:MegaHandler.java

private int login_process(JSONObject json, long[] password_aes) throws IOException {

    String master_key_b64 = null;
    try {//from  w  w  w  .j  ava 2 s  . c om
        master_key_b64 = json.getString("k");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (master_key_b64 == null || master_key_b64.isEmpty())
        return -1;

    long[] encrypted_master_key = MegaCrypt.base64_to_a32(master_key_b64);
    master_key = MegaCrypt.decrypt_key(encrypted_master_key, password_aes);

    if (json.has("csid")) {
        String encrypted_rsa_private_key_b64 = null;
        try {
            encrypted_rsa_private_key_b64 = json.getString("privk");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        long[] encrypted_rsa_private_key = MegaCrypt.base64_to_a32(encrypted_rsa_private_key_b64);
        long[] rsa_private_key = MegaCrypt.decrypt_key(encrypted_rsa_private_key, master_key);
        String private_key = MegaCrypt.a32_to_str(rsa_private_key);

        this.rsa_private_key = new BigInteger[4];
        for (int i = 0; i < 4; i++) {
            int l = ((((int) private_key.charAt(0)) * 256 + ((int) private_key.charAt(1)) + 7) / 8) + 2;
            this.rsa_private_key[i] = MegaCrypt.mpi_to_int(private_key.substring(0, l));
            private_key = private_key.substring(l);
        }

        BigInteger encrypted_sid = null;
        try {
            encrypted_sid = MegaCrypt.mpi_to_int(MegaCrypt.base64_url_decode(json.getString("csid")));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        BigInteger modulus = this.rsa_private_key[0].multiply(this.rsa_private_key[1]);
        BigInteger privateExponent = this.rsa_private_key[2];

        BigInteger sid = null;
        try {
            PrivateKey privateKey = KeyFactory.getInstance("RSA")
                    .generatePrivate(new RSAPrivateKeySpec(modulus, privateExponent));
            Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // PyCrypt can handle >256 bit length... what the fuck... sometimes i get 257
            if (encrypted_sid.toByteArray().length > 256) {
                Random rg = new Random();
                sequence_number = rg.nextInt(Integer.MAX_VALUE);
                return -2; // lets get a new seession
            }
            sid = new BigInteger(cipher.doFinal(encrypted_sid.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

        String sidS = sid.toString(16);
        if (sidS.length() % 2 != 0)
            sidS = "0" + sidS;
        try {
            byte[] sidsnohex = MegaCrypt.decodeHexString(sidS);
            this.sid = MegaCrypt.base64_url_encode(new String(sidsnohex, "ISO-8859-1").substring(0, 43));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
    return 0;
}

From source file:compiler.downloader.MegaHandler.java

private int login_process(JSONObject json, long[] password_aes) throws IOException {

    String master_key_b64 = null;
    try {//w w w.  j a v a 2 s . co m
        master_key_b64 = json.getString("k");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (master_key_b64 == null || master_key_b64.isEmpty()) {
        return -1;
    }

    long[] encrypted_master_key = MegaCrypt.base64_to_a32(master_key_b64);
    master_key = MegaCrypt.decrypt_key(encrypted_master_key, password_aes);

    if (json.has("csid")) {
        String encrypted_rsa_private_key_b64 = null;
        try {
            encrypted_rsa_private_key_b64 = json.getString("privk");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        long[] encrypted_rsa_private_key = MegaCrypt.base64_to_a32(encrypted_rsa_private_key_b64);
        long[] rsa_private_key = MegaCrypt.decrypt_key(encrypted_rsa_private_key, master_key);
        String private_key = MegaCrypt.a32_to_str(rsa_private_key);

        BigInteger[] rsa_private_key1 = new BigInteger[4];
        for (int i = 0; i < 4; i++) {
            int l = ((((int) private_key.charAt(0)) * 256 + ((int) private_key.charAt(1)) + 7) / 8) + 2;
            rsa_private_key1[i] = MegaCrypt.mpi_to_int(private_key.substring(0, l));
            private_key = private_key.substring(l);
        }

        BigInteger encrypted_sid = null;
        try {
            encrypted_sid = MegaCrypt.mpi_to_int(MegaCrypt.base64_url_decode(json.getString("csid")));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        BigInteger modulus = rsa_private_key1[0].multiply(rsa_private_key1[1]);
        BigInteger privateExponent = rsa_private_key1[2];

        BigInteger sid = null;
        try {
            PrivateKey privateKey = KeyFactory.getInstance("RSA")
                    .generatePrivate(new RSAPrivateKeySpec(modulus, privateExponent));
            Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // PyCrypt can handle >256 bit length... what the fuck... sometimes i get 257
            if (encrypted_sid.toByteArray().length > 256) {
                Random rg = new Random();
                sequence_number = rg.nextInt(Integer.MAX_VALUE);
                return -2; // lets get a new seession
            }
            sid = new BigInteger(cipher.doFinal(encrypted_sid.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

        String sidS = sid.toString(16);
        if (sidS.length() % 2 != 0) {
            sidS = "0" + sidS;
        }
        try {
            byte[] sidsnohex = MegaCrypt.decodeHexString(sidS);
            this.sid = MegaCrypt.base64_url_encode(new String(sidsnohex, "ISO-8859-1").substring(0, 43));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
    return 0;
}

From source file:org.dasein.cloud.google.compute.server.ServerSupport.java

private JSONObject jsonEncode(KeyPair keys) throws InternalException {
    JSONObject returnJson = new JSONObject();
    try {//from ww  w  .  j  av  a2 s  .co  m
        KeyFactory factory = KeyFactory.getInstance("RSA");

        RSAPublicKeySpec pubSpec = factory.getKeySpec(keys.getPublic(), RSAPublicKeySpec.class);

        BigInteger modulus = pubSpec.getModulus();
        BigInteger exponent = pubSpec.getPublicExponent();

        BaseEncoding stringEncoder = BaseEncoding.base64();

        // Strip out the leading 0 byte in the modulus.
        byte[] arr = Arrays.copyOfRange(modulus.toByteArray(), 1, modulus.toByteArray().length);

        returnJson.put("modulus", stringEncoder.encode(arr).replaceAll("\n", ""));
        returnJson.put("exponent", stringEncoder.encode(exponent.toByteArray()).replaceAll("\n", ""));
    } catch (Exception e) {
        throw new InternalException(e);
    }

    return returnJson;
}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

/**
 * Converts NSS key ID from a signed, variable-length hexadecimal number
 * into a 20 byte array, which will be identical to the original byte array.
 *//*from   ww w.  ja  v a  2s  .  c  om*/
public static byte[] decodeKeyID(String id) {

    BigInteger value = new BigInteger(id, 16);
    byte[] array = value.toByteArray();

    if (array.length > KEY_ID_LENGTH) {
        throw new IllegalArgumentException("Unable to decode Key ID: " + id);
    }

    if (array.length < KEY_ID_LENGTH) {

        // extend the array with most significant bit
        byte[] tmp = array;
        array = new byte[KEY_ID_LENGTH];

        // calculate the extension
        int p = KEY_ID_LENGTH - tmp.length;

        // create filler byte based op the most significant bit
        byte b = (byte) (value.signum() >= 0 ? 0x00 : 0xff);

        // fill the extension with the filler byte
        Arrays.fill(array, 0, p, b);

        // copy the original array
        System.arraycopy(tmp, 0, array, p, tmp.length);
    }

    return array;
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

private void startOutgoingCall() {
    configureDeviceForCall();//from  w  w w  .  j av a  2  s .  c o m
    showNotification();
    startConnectingSound();
    dispatchStateChanged(STATE_REQUESTING);
    AndroidUtilities.runOnUIThread(new Runnable() {
        @Override
        public void run() {
            NotificationCenter.getInstance().postNotificationName(NotificationCenter.didStartedCall);
        }
    });
    final byte[] salt = new byte[256];
    Utilities.random.nextBytes(salt);

    TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig();
    req.random_length = 256;
    req.version = MessagesStorage.lastSecretVersion;
    callReqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
        @Override
        public void run(TLObject response, TLRPC.TL_error error) {
            callReqId = 0;
            if (error == null) {
                TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response;
                if (response instanceof TLRPC.TL_messages_dhConfig) {
                    if (!Utilities.isGoodPrime(res.p, res.g)) {
                        callFailed();
                        return;
                    }
                    MessagesStorage.secretPBytes = res.p;
                    MessagesStorage.secretG = res.g;
                    MessagesStorage.lastSecretVersion = res.version;
                    MessagesStorage.getInstance().saveSecretParams(MessagesStorage.lastSecretVersion,
                            MessagesStorage.secretG, MessagesStorage.secretPBytes);
                }
                final byte[] salt = new byte[256];
                for (int a = 0; a < 256; a++) {
                    salt[a] = (byte) ((byte) (Utilities.random.nextDouble() * 256) ^ res.random[a]);
                }

                BigInteger i_g_a = BigInteger.valueOf(MessagesStorage.secretG);
                i_g_a = i_g_a.modPow(new BigInteger(1, salt), new BigInteger(1, MessagesStorage.secretPBytes));
                byte[] g_a = i_g_a.toByteArray();
                if (g_a.length > 256) {
                    byte[] correctedAuth = new byte[256];
                    System.arraycopy(g_a, 1, correctedAuth, 0, 256);
                    g_a = correctedAuth;
                }

                TLRPC.TL_phone_requestCall reqCall = new TLRPC.TL_phone_requestCall();
                reqCall.user_id = MessagesController.getInputUser(user);
                reqCall.protocol = new TLRPC.TL_phoneCallProtocol();
                reqCall.protocol.udp_p2p = reqCall.protocol.udp_reflector = true;
                reqCall.protocol.min_layer = CALL_MIN_LAYER;
                reqCall.protocol.max_layer = CALL_MAX_LAYER;
                VoIPService.this.g_a = g_a;
                reqCall.g_a_hash = Utilities.computeSHA256(g_a, 0, g_a.length);
                reqCall.random_id = Utilities.random.nextInt();

                ConnectionsManager.getInstance().sendRequest(reqCall, new RequestDelegate() {
                    @Override
                    public void run(final TLObject response, final TLRPC.TL_error error) {
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                if (error == null) {
                                    call = ((TLRPC.TL_phone_phoneCall) response).phone_call;
                                    a_or_b = salt;
                                    dispatchStateChanged(STATE_WAITING);
                                    if (endCallAfterRequest) {
                                        hangUp();
                                        return;
                                    }
                                    if (pendingUpdates.size() > 0 && call != null) {
                                        for (TLRPC.PhoneCall call : pendingUpdates) {
                                            onCallUpdated(call);
                                        }
                                        pendingUpdates.clear();
                                    }
                                    timeoutRunnable = new Runnable() {
                                        @Override
                                        public void run() {
                                            timeoutRunnable = null;
                                            TLRPC.TL_phone_discardCall req = new TLRPC.TL_phone_discardCall();
                                            req.peer = new TLRPC.TL_inputPhoneCall();
                                            req.peer.access_hash = call.access_hash;
                                            req.peer.id = call.id;
                                            req.reason = new TLRPC.TL_phoneCallDiscardReasonMissed();
                                            ConnectionsManager.getInstance().sendRequest(req,
                                                    new RequestDelegate() {
                                                        @Override
                                                        public void run(TLObject response,
                                                                TLRPC.TL_error error) {
                                                            if (error != null) {
                                                                FileLog.e(
                                                                        "error on phone.discardCall: " + error);
                                                            } else {
                                                                FileLog.d("phone.discardCall " + response);
                                                            }
                                                            AndroidUtilities.runOnUIThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    callFailed();
                                                                }
                                                            });
                                                        }
                                                    }, ConnectionsManager.RequestFlagFailOnServerErrors);
                                        }
                                    };
                                    AndroidUtilities.runOnUIThread(timeoutRunnable,
                                            MessagesController.getInstance().callReceiveTimeout);
                                } else {
                                    if (error.code == 400
                                            && "PARTICIPANT_VERSION_OUTDATED".equals(error.text)) {
                                        callFailed(VoIPController.ERROR_PEER_OUTDATED);
                                    } else if (error.code == 403
                                            && "USER_PRIVACY_RESTRICTED".equals(error.text)) {
                                        callFailed(VoIPController.ERROR_PRIVACY);
                                    } else if (error.code == 406) {
                                        callFailed(VoIPController.ERROR_LOCALIZED);
                                    } else {
                                        FileLog.e("Error on phone.requestCall: " + error);
                                        callFailed();
                                    }
                                }
                            }
                        });
                    }
                }, ConnectionsManager.RequestFlagFailOnServerErrors);
            } else {
                FileLog.e("Error on getDhConfig " + error);
                callFailed();
            }
        }
    }, ConnectionsManager.RequestFlagFailOnServerErrors);
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

private void processAcceptedCall() {
    dispatchStateChanged(STATE_EXCHANGING_KEYS);
    BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes);
    BigInteger i_authKey = new BigInteger(1, call.g_b);

    if (!Utilities.isGoodGaAndGb(i_authKey, p)) {
        FileLog.w("stopping VoIP service, bad Ga and Gb");
        callFailed();//from   ww w .j ava  2s  . c o  m
        return;
    }

    i_authKey = i_authKey.modPow(new BigInteger(1, a_or_b), p);

    byte[] authKey = i_authKey.toByteArray();
    if (authKey.length > 256) {
        byte[] correctedAuth = new byte[256];
        System.arraycopy(authKey, authKey.length - 256, correctedAuth, 0, 256);
        authKey = correctedAuth;
    } else if (authKey.length < 256) {
        byte[] correctedAuth = new byte[256];
        System.arraycopy(authKey, 0, correctedAuth, 256 - authKey.length, authKey.length);
        for (int a = 0; a < 256 - authKey.length; a++) {
            authKey[a] = 0;
        }
        authKey = correctedAuth;
    }
    byte[] authKeyHash = Utilities.computeSHA1(authKey);
    byte[] authKeyId = new byte[8];
    System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyId, 0, 8);
    long fingerprint = Utilities.bytesToLong(authKeyId);
    this.authKey = authKey;
    keyFingerprint = fingerprint;
    TLRPC.TL_phone_confirmCall req = new TLRPC.TL_phone_confirmCall();
    req.g_a = g_a;
    req.key_fingerprint = fingerprint;
    req.peer = new TLRPC.TL_inputPhoneCall();
    req.peer.id = call.id;
    req.peer.access_hash = call.access_hash;
    req.protocol = new TLRPC.TL_phoneCallProtocol();
    req.protocol.max_layer = CALL_MAX_LAYER;
    req.protocol.min_layer = CALL_MIN_LAYER;
    req.protocol.udp_p2p = req.protocol.udp_reflector = true;
    ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
        @Override
        public void run(final TLObject response, final TLRPC.TL_error error) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    if (error != null) {
                        callFailed();
                    } else {
                        call = ((TLRPC.TL_phone_phoneCall) response).phone_call;
                        initiateActualEncryptedCall();
                    }
                }
            });
        }
    });
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

public void acceptIncomingCall() {
    stopRinging();//w  w  w.j a v  a  2  s  .  c  om
    showNotification();
    configureDeviceForCall();
    startConnectingSound();
    dispatchStateChanged(STATE_EXCHANGING_KEYS);
    AndroidUtilities.runOnUIThread(new Runnable() {
        @Override
        public void run() {
            NotificationCenter.getInstance().postNotificationName(NotificationCenter.didStartedCall);
        }
    });
    TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig();
    req.random_length = 256;
    req.version = MessagesStorage.lastSecretVersion;
    ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
        @Override
        public void run(TLObject response, TLRPC.TL_error error) {
            if (error == null) {
                TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response;
                if (response instanceof TLRPC.TL_messages_dhConfig) {
                    if (!Utilities.isGoodPrime(res.p, res.g)) {
                        /*acceptingChats.remove(encryptedChat.id);
                        declineSecretChat(encryptedChat.id);*/
                        FileLog.e("stopping VoIP service, bad prime");
                        callFailed();
                        return;
                    }

                    MessagesStorage.secretPBytes = res.p;
                    MessagesStorage.secretG = res.g;
                    MessagesStorage.lastSecretVersion = res.version;
                    MessagesStorage.getInstance().saveSecretParams(MessagesStorage.lastSecretVersion,
                            MessagesStorage.secretG, MessagesStorage.secretPBytes);
                }
                byte[] salt = new byte[256];
                for (int a = 0; a < 256; a++) {
                    salt[a] = (byte) ((byte) (Utilities.random.nextDouble() * 256) ^ res.random[a]);
                }
                a_or_b = salt;
                BigInteger g_b = BigInteger.valueOf(MessagesStorage.secretG);
                BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes);
                g_b = g_b.modPow(new BigInteger(1, salt), p);
                g_a_hash = call.g_a_hash;

                byte[] g_b_bytes = g_b.toByteArray();
                if (g_b_bytes.length > 256) {
                    byte[] correctedAuth = new byte[256];
                    System.arraycopy(g_b_bytes, 1, correctedAuth, 0, 256);
                    g_b_bytes = correctedAuth;
                }

                TLRPC.TL_phone_acceptCall req = new TLRPC.TL_phone_acceptCall();
                req.g_b = g_b_bytes;
                //req.key_fingerprint = Utilities.bytesToLong(authKeyId);
                req.peer = new TLRPC.TL_inputPhoneCall();
                req.peer.id = call.id;
                req.peer.access_hash = call.access_hash;
                req.protocol = new TLRPC.TL_phoneCallProtocol();
                req.protocol.udp_p2p = req.protocol.udp_reflector = true;
                req.protocol.min_layer = CALL_MIN_LAYER;
                req.protocol.max_layer = CALL_MAX_LAYER;
                ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                    @Override
                    public void run(final TLObject response, final TLRPC.TL_error error) {
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                if (error == null) {
                                    FileLog.w("accept call ok! " + response);
                                    call = ((TLRPC.TL_phone_phoneCall) response).phone_call;
                                    if (call instanceof TLRPC.TL_phoneCallDiscarded) {
                                        onCallUpdated(call);
                                    } /*else{
                                      initiateActualEncryptedCall();
                                      }*/
                                } else {
                                    FileLog.e("Error on phone.acceptCall: " + error);
                                    callFailed();
                                }
                            }
                        });
                    }
                }, ConnectionsManager.RequestFlagFailOnServerErrors);
            } else {
                //acceptingChats.remove(encryptedChat.id);
                callFailed();
            }
        }
    });
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

public void onCallUpdated(TLRPC.PhoneCall call) {
    if (this.call == null) {
        pendingUpdates.add(call);//from w  w  w .ja  v a 2 s .  c om
        return;
    }
    if (call == null)
        return;
    if (call.id != this.call.id) {
        if (BuildVars.DEBUG_VERSION)
            FileLog.w("onCallUpdated called with wrong call id (got " + call.id + ", expected " + this.call.id
                    + ")");
        return;
    }
    if (call.access_hash == 0)
        call.access_hash = this.call.access_hash;
    if (BuildVars.DEBUG_VERSION) {
        FileLog.d("Call updated: " + call);
        dumpCallObject();
    }
    this.call = call;
    if (call instanceof TLRPC.TL_phoneCallDiscarded) {
        needSendDebugLog = call.need_debug;
        FileLog.d("call discarded, stopping service");
        if (call.reason instanceof TLRPC.TL_phoneCallDiscardReasonBusy) {
            dispatchStateChanged(STATE_BUSY);
            playingSound = true;
            soundPool.play(spBusyId, 1, 1, 0, -1, 1);
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    soundPool.release();
                    if (isBtHeadsetConnected)
                        ((AudioManager) ApplicationLoader.applicationContext.getSystemService(AUDIO_SERVICE))
                                .stopBluetoothSco();
                }
            }, 2500);
            stopSelf();
        } else {
            callEnded();
        }
        if (call.need_rating) {
            startRatingActivity();
        }
    } else if (call instanceof TLRPC.TL_phoneCall && authKey == null) {
        if (call.g_a_or_b == null) {
            FileLog.w("stopping VoIP service, Ga == null");
            callFailed();
            return;
        }
        if (!Arrays.equals(g_a_hash, Utilities.computeSHA256(call.g_a_or_b, 0, call.g_a_or_b.length))) {
            FileLog.w("stopping VoIP service, Ga hash doesn't match");
            callFailed();
            return;
        }
        g_a = call.g_a_or_b;
        BigInteger g_a = new BigInteger(1, call.g_a_or_b);
        BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes);

        if (!Utilities.isGoodGaAndGb(g_a, p)) {
            FileLog.w("stopping VoIP service, bad Ga and Gb (accepting)");
            callFailed();
            return;
        }
        g_a = g_a.modPow(new BigInteger(1, a_or_b), p);

        byte[] authKey = g_a.toByteArray();
        if (authKey.length > 256) {
            byte[] correctedAuth = new byte[256];
            System.arraycopy(authKey, authKey.length - 256, correctedAuth, 0, 256);
            authKey = correctedAuth;
        } else if (authKey.length < 256) {
            byte[] correctedAuth = new byte[256];
            System.arraycopy(authKey, 0, correctedAuth, 256 - authKey.length, authKey.length);
            for (int a = 0; a < 256 - authKey.length; a++) {
                authKey[a] = 0;
            }
            authKey = correctedAuth;
        }
        byte[] authKeyHash = Utilities.computeSHA1(authKey);
        byte[] authKeyId = new byte[8];
        System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyId, 0, 8);
        VoIPService.this.authKey = authKey;
        keyFingerprint = Utilities.bytesToLong(authKeyId);

        if (keyFingerprint != call.key_fingerprint) {
            FileLog.w("key fingerprints don't match");
            callFailed();
            return;
        }

        initiateActualEncryptedCall();
    } else if (call instanceof TLRPC.TL_phoneCallAccepted && authKey == null) {
        processAcceptedCall();
    } else {
        if (currentState == STATE_WAITING && call.receive_date != 0) {
            dispatchStateChanged(STATE_RINGING);
            FileLog.d("!!!!!! CALL RECEIVED");
            if (spPlayID != 0)
                soundPool.stop(spPlayID);
            spPlayID = soundPool.play(spRingbackID, 1, 1, 0, -1, 1);
            if (timeoutRunnable != null) {
                AndroidUtilities.cancelRunOnUIThread(timeoutRunnable);
                timeoutRunnable = null;
            }
            timeoutRunnable = new Runnable() {
                @Override
                public void run() {
                    timeoutRunnable = null;
                    declineIncomingCall(DISCARD_REASON_MISSED, null);
                }
            };
            AndroidUtilities.runOnUIThread(timeoutRunnable, MessagesController.getInstance().callRingTimeout);
        }
    }
}

From source file:org.apache.xml.security.stax.ext.XMLSecurityUtils.java

public static void createKeyValueTokenStructure(AbstractOutputProcessor abstractOutputProcessor,
        OutputProcessorChain outputProcessorChain, PublicKey publicKey)
        throws XMLStreamException, XMLSecurityException {

    if (publicKey == null) {
        throw new XMLSecurityException("stax.signature.publicKeyOrCertificateMissing");
    }//from  ww  w  .  ja  v a  2  s . c o m

    String algorithm = publicKey.getAlgorithm();

    abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
            XMLSecurityConstants.TAG_dsig_KeyValue, true, null);

    if ("RSA".equals(algorithm)) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_RSAKeyValue, false, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Modulus, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(rsaPublicKey.getModulus().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Modulus);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Exponent, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(rsaPublicKey.getPublicExponent().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Exponent);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_RSAKeyValue);
    } else if ("DSA".equals(algorithm)) {
        DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey;
        BigInteger j = dsaPublicKey.getParams().getP().subtract(BigInteger.ONE)
                .divide(dsaPublicKey.getParams().getQ());
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_DSAKeyValue, false, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_P, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getP().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_P);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Q, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getQ().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Q);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_G, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getG().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_G);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Y, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(dsaPublicKey.getY().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Y);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_J, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(j.toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_J);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_DSAKeyValue);
    } else if ("EC".equals(algorithm)) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;

        List<XMLSecAttribute> attributes = new ArrayList<XMLSecAttribute>(1);
        attributes.add(abstractOutputProcessor.createAttribute(XMLSecurityConstants.ATT_NULL_URI,
                "urn:oid:" + ECDSAUtils.getOIDFromPublicKey(ecPublicKey)));
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_ECKeyValue, true, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_NamedCurve, false, attributes);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_NamedCurve);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_PublicKey, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(
                        ECDSAUtils.encodePoint(ecPublicKey.getW(), ecPublicKey.getParams().getCurve())));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_PublicKey);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_ECKeyValue);
    }

    abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
            XMLSecurityConstants.TAG_dsig_KeyValue);
}