Example usage for java.math BigInteger modPow

List of usage examples for java.math BigInteger modPow

Introduction

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

Prototype

public BigInteger modPow(BigInteger exponent, BigInteger m) 

Source Link

Document

Returns a BigInteger whose value is (thisexponent mod m).

Usage

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testPSSPrefix() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);// www  . ja  v  a 2 s.co m
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA1withRSAandMGF1");
    signature.initSign(authnPrivateKey);

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    RSAPublicKey rsaPublicKey = (RSAPublicKey) authnPublicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    String paddedMessage = new String(Hex.encodeHex(messageBigInteger.toByteArray()));
    LOG.debug("padded message: " + paddedMessage);
    assertTrue(paddedMessage.endsWith("bc"));
}

From source file:acp.sdk.SecureUtil.java

/**
 * /*  www .  jav  a2s .  co m*/
 * @param tPIN
 * @param iPan
 * @param publicKey
 * @return
 */
public String assymEncrypt(String tPIN, String iPan, RSAPublicKey publicKey) {

    System.out.println("SampleHashMap::assymEncrypt([" + tPIN + "])");
    System.out.println("SampleHashMap::assymEncrypt(PIN =[" + tPIN + "])");

    try {
        int tKeyLength = 1024;
        int tBlockSize = tKeyLength / 8;

        byte[] tTemp = null;

        tTemp = SecureUtil.pin2PinBlockWithCardNO(tPIN, iPan);
        tTemp = addPKCS1Padding(tTemp, tBlockSize);

        BigInteger tPlainText = new BigInteger(tTemp);
        BigInteger tCipherText = tPlainText.modPow(publicKey.getPublicExponent(), publicKey.getModulus());

        byte[] tCipherBytes = tCipherText.toByteArray();
        int tCipherLength = tCipherBytes.length;
        if (tCipherLength > tBlockSize) {
            byte[] tTempBytes = new byte[tBlockSize];
            System.arraycopy(tCipherBytes, tCipherLength - tBlockSize, tTempBytes, 0, tBlockSize);
            tCipherBytes = tTempBytes;
        } else if (tCipherLength < tBlockSize) {
            byte[] tTempBytes = new byte[tBlockSize];
            for (int i = 0; i < tBlockSize - tCipherLength; i++) {
                tTempBytes[i] = 0x00;
            }
            System.arraycopy(tCipherBytes, 0, tTempBytes, tBlockSize - tCipherLength, tCipherLength);
            tCipherBytes = tTempBytes;
        }
        String tEncryptPIN = new String(SecureUtil.base64Encode(tCipherBytes));

        System.out.println("SampleHashMap::assymEncrypt(EncryptCardNo =[" + tEncryptPIN + "])");

        return tEncryptPIN;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        return tPIN;
    } catch (Error e) {
        e.printStackTrace(System.out);
        return tPIN;
    }
}

From source file:org.jmangos.realm.network.packet.auth.client.CMD_AUTH_LOGON_CHALLENGE.java

@Override
protected void readImpl() throws BufferUnderflowException, RuntimeException {

    readC();//from w  w  w.ja v a2s  . c  om
    if (readC() == WoWAuthResponse.WOW_SUCCESS.getMessageId()) {
        final SecureRandom random = new SecureRandom();
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA-1");
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
            return;
        }
        final BigInteger k = new BigInteger("3");
        final byte[] Bb = readB(32);
        final BigInteger g = new BigInteger(readB(readC()));
        final byte[] Nb = readB(readC());
        final byte[] saltb = readB(32);
        /* byte[] unk3 = */readB(16);
        readC();
        ArrayUtils.reverse(Bb);
        final BigInteger B = new BigInteger(1, Bb);
        ArrayUtils.reverse(Bb);
        ArrayUtils.reverse(Nb);
        final BigInteger N = new BigInteger(1, Nb);
        ArrayUtils.reverse(Nb);
        final BigInteger a = new BigInteger(1, random.generateSeed(19));

        final byte[] passhash = sha.digest(this.config.AUTH_LOGIN.toUpperCase().concat(":")
                .concat(this.config.AUTH_PASSWORD.toUpperCase()).getBytes(Charset.forName("UTF-8")));
        sha.update(saltb);
        sha.update(passhash);

        final byte[] xhash = sha.digest();
        ArrayUtils.reverse(xhash);
        final BigInteger x = new BigInteger(1, xhash);
        logger.debug("x:" + x.toString(16).toUpperCase());
        final BigInteger v = g.modPow(x, N);
        logger.debug("v:" + v.toString(16).toUpperCase());
        final BigInteger A = g.modPow(a, N);
        logger.debug("A:" + A.toString(16).toUpperCase());
        logger.debug("B:" + B.toString(16).toUpperCase());
        this.ahash = A.toByteArray();
        ArrayUtils.reverse(this.ahash);
        sha.update(this.ahash);
        sha.update(Bb);
        final byte[] hashu = sha.digest();
        ArrayUtils.reverse(hashu);
        final BigInteger u = new BigInteger(1, hashu);
        logger.debug("u:" + u.toString(16).toUpperCase());
        final BigInteger S = (B.subtract(k.multiply(g.modPow(x, N)))).modPow(a.add(u.multiply(x)), N);

        final byte[] full_S = S.toByteArray();
        ArrayUtils.reverse(full_S);
        logger.debug("t:" + StringUtils.toHexString(full_S));
        final byte[] s1_hash = new byte[16];
        final byte[] s2_hash = new byte[16];
        for (int i = 0; i < 16; i++) {
            s1_hash[i] = full_S[i * 2];
            s2_hash[i] = full_S[(i * 2) + 1];
        }
        final byte[] t1 = sha.digest(s1_hash);
        final byte[] t2 = sha.digest(s2_hash);
        final byte[] vK = new byte[40];
        for (int i = 0; i < 20; i++) {
            vK[i * 2] = t1[i];
            vK[(i * 2) + 1] = t2[i];
        }

        byte[] hash = new byte[20];
        logger.debug("N:" + N.toString(16).toUpperCase());
        hash = sha.digest(Nb);

        logger.debug("hash:" + new BigInteger(1, hash).toString(16).toUpperCase());

        byte[] gH = new byte[20];
        sha.update(g.toByteArray());
        gH = sha.digest();
        for (int i = 0; i < 20; ++i) {
            hash[i] ^= gH[i];
        }

        byte[] t4 = new byte[20];
        t4 = sha.digest(this.config.AUTH_LOGIN.toUpperCase().getBytes(Charset.forName("UTF-8")));

        sha.update(hash);
        logger.debug("hash:" + StringUtils.toHexString(hash));
        sha.update(t4);
        logger.debug("t4:" + StringUtils.toHexString(t4));
        sha.update(saltb);
        logger.debug("saltb:" + StringUtils.toHexString(saltb));
        sha.update(this.ahash);
        logger.debug("ahash:" + StringUtils.toHexString(this.ahash));
        sha.update(Bb);
        logger.debug("Bb:" + StringUtils.toHexString(Bb));
        sha.update(vK);
        logger.debug("vK:" + StringUtils.toHexString(vK));
        this.m1 = sha.digest();

        sha.update(this.ahash);
        sha.update(this.m1);
        sha.update(vK);
        logger.debug("m1 value" + StringUtils.toHexString(this.m1));
        @SuppressWarnings("unused")
        final byte[] m2 = sha.digest();

        final ChannelPipeline pipeline = getClient().getChannel().getPipeline();
        ((RealmToAuthChannelHandler) pipeline.getLast()).setSeed(vK);

    } else {
        getChannel().getPipeline().remove("handler");
        getChannel().getPipeline().remove("eventlog");
        getChannel().getPipeline().remove("executor");
        getChannel().close();
        getChannel().getFactory().releaseExternalResources();
    }
}

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

private void startOutgoingCall() {
    configureDeviceForCall();//from w ww  .  j  a  va 2s  . c  om
    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

public void acceptIncomingCall() {
    stopRinging();/*w w  w .j  a v  a  2s. c o m*/
    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

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   w  w  w  .j a  v  a 2 s.c  om*/
        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 onCallUpdated(TLRPC.PhoneCall call) {
    if (this.call == null) {
        pendingUpdates.add(call);/*from   w w  w.j a  va2 s. c  o m*/
        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.telegram.messenger.MessagesController.java

public void acceptSecretChat(final TLRPC.EncryptedChat encryptedChat) {
    if (acceptingChats.get(encryptedChat.id) != null) {
        return;/*from  w w w .j  a v  a2 s .c  om*/
    }
    acceptingChats.put(encryptedChat.id, encryptedChat);
    TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig();
    req.random_length = 256;
    req.version = MessagesStorage.lastSecretVersion;
    ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() {
        @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);
                        return;
                    }

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

                if (!Utilities.isGoodGaAndGb(g_a, p)) {
                    acceptingChats.remove(encryptedChat.id);
                    declineSecretChat(encryptedChat.id);
                    return;
                }

                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;
                }

                g_a = g_a.modPow(new BigInteger(1, salt), 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);
                encryptedChat.auth_key = authKey;

                TLRPC.TL_messages_acceptEncryption req2 = new TLRPC.TL_messages_acceptEncryption();
                req2.g_b = g_b_bytes;
                req2.peer = new TLRPC.TL_inputEncryptedChat();
                req2.peer.chat_id = encryptedChat.id;
                req2.peer.access_hash = encryptedChat.access_hash;
                req2.key_fingerprint = Utilities.bytesToLong(authKeyId);
                ConnectionsManager.Instance.performRpc(req2, new RPCRequest.RPCRequestDelegate() {
                    @Override
                    public void run(TLObject response, TLRPC.TL_error error) {
                        acceptingChats.remove(encryptedChat.id);
                        if (error == null) {
                            final TLRPC.EncryptedChat newChat = (TLRPC.EncryptedChat) response;
                            newChat.auth_key = encryptedChat.auth_key;
                            newChat.user_id = encryptedChat.user_id;
                            MessagesStorage.Instance.updateEncryptedChat(newChat);
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    encryptedChats.put(newChat.id, newChat);
                                    NotificationCenter.Instance.postNotificationName(encryptedChatUpdated,
                                            newChat);
                                }
                            });
                        }
                    }
                }, null, true, RPCRequest.RPCRequestClassGeneric);
            } else {
                acceptingChats.remove(encryptedChat.id);
            }
        }
    }, null, true, RPCRequest.RPCRequestClassGeneric);
}

From source file:org.telegram.messenger.MessagesController.java

public void startSecretChat(final Context context, final TLRPC.User user) {
    if (user == null) {
        return;/* www.  jav  a  2 s  . c o  m*/
    }
    final ProgressDialog progressDialog = new ProgressDialog(context);
    progressDialog.setMessage(context.getString(R.string.Loading));
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.setCancelable(false);
    progressDialog.show();
    TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig();
    req.random_length = 256;
    req.version = MessagesStorage.lastSecretVersion;
    ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() {
        @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)) {
                        Utilities.RunOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        progressDialog.dismiss();
                                    }
                                } catch (Exception e) {
                                    FileLog.e("tmessages", e);
                                }
                            }
                        });
                        return;
                    }
                    MessagesStorage.secretPBytes = res.p;
                    MessagesStorage.secretG = res.g;
                    MessagesStorage.lastSecretVersion = res.version;
                    MessagesStorage.Instance.saveSecretParams(MessagesStorage.lastSecretVersion,
                            MessagesStorage.secretG, MessagesStorage.secretPBytes);
                }
                final byte[] salt = new byte[256];
                for (int a = 0; a < 256; a++) {
                    salt[a] = (byte) ((byte) (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_messages_requestEncryption req2 = new TLRPC.TL_messages_requestEncryption();
                req2.g_a = g_a;
                req2.user_id = getInputUser(user);
                req2.random_id = (int) (random.nextDouble() * Integer.MAX_VALUE);
                ConnectionsManager.Instance.performRpc(req2, new RPCRequest.RPCRequestDelegate() {
                    @Override
                    public void run(final TLObject response, TLRPC.TL_error error) {
                        if (error == null) {
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        try {
                                            progressDialog.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                    }
                                    TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) response;
                                    chat.user_id = chat.participant_id;
                                    encryptedChats.put(chat.id, chat);
                                    chat.a_or_b = salt;
                                    TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
                                    dialog.id = ((long) chat.id) << 32;
                                    dialog.unread_count = 0;
                                    dialog.top_message = 0;
                                    dialog.last_message_date = ConnectionsManager.Instance.getCurrentTime();
                                    dialogs_dict.put(dialog.id, dialog);
                                    dialogs.add(dialog);
                                    dialogsServerOnly.clear();
                                    Collections.sort(dialogs, new Comparator<TLRPC.TL_dialog>() {
                                        @Override
                                        public int compare(TLRPC.TL_dialog tl_dialog,
                                                TLRPC.TL_dialog tl_dialog2) {
                                            if (tl_dialog.last_message_date == tl_dialog2.last_message_date) {
                                                return 0;
                                            } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) {
                                                return 1;
                                            } else {
                                                return -1;
                                            }
                                        }
                                    });
                                    for (TLRPC.TL_dialog d : dialogs) {
                                        if ((int) d.id != 0) {
                                            dialogsServerOnly.add(d);
                                        }
                                    }
                                    NotificationCenter.Instance.postNotificationName(dialogsNeedReload);
                                    MessagesStorage.Instance.putEncryptedChat(chat, user, dialog);
                                    NotificationCenter.Instance.postNotificationName(encryptedChatCreated,
                                            chat);
                                }
                            });
                        } else {
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        try {
                                            progressDialog.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                        builder.setTitle(context.getString(R.string.AppName));
                                        builder.setMessage(String.format(
                                                context.getString(R.string.CreateEncryptedChatOutdatedError),
                                                user.first_name, user.first_name));
                                        builder.setPositiveButton(
                                                ApplicationLoader.applicationContext.getString(R.string.OK),
                                                null);
                                        builder.show().setCanceledOnTouchOutside(true);
                                    }
                                }
                            });
                        }
                    }
                }, null, true,
                        RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
            } else {
                Utilities.RunOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!((ActionBarActivity) context).isFinishing()) {
                            try {
                                progressDialog.dismiss();
                            } catch (Exception e) {
                                FileLog.e("tmessages", e);
                            }
                        }
                    }
                });
            }
        }
    }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
}

From source file:org.telegram.messenger.MessagesController.java

public void processAcceptedSecretChat(final TLRPC.EncryptedChat encryptedChat) {
    BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes);
    BigInteger i_authKey = new BigInteger(1, encryptedChat.g_a_or_b);

    if (!Utilities.isGoodGaAndGb(i_authKey, p)) {
        declineSecretChat(encryptedChat.id);
        return;//from  w  ww  .  j a  va 2 s  .  c  o m
    }

    i_authKey = i_authKey.modPow(new BigInteger(1, encryptedChat.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);
    if (encryptedChat.key_fingerprint == fingerprint) {
        encryptedChat.auth_key = authKey;
        MessagesStorage.Instance.updateEncryptedChat(encryptedChat);
        Utilities.RunOnUIThread(new Runnable() {
            @Override
            public void run() {
                encryptedChats.put(encryptedChat.id, encryptedChat);
                NotificationCenter.Instance.postNotificationName(encryptedChatUpdated, encryptedChat);
            }
        });
    } else {
        final TLRPC.TL_encryptedChatDiscarded newChat = new TLRPC.TL_encryptedChatDiscarded();
        newChat.id = encryptedChat.id;
        newChat.user_id = encryptedChat.user_id;
        newChat.auth_key = encryptedChat.auth_key;
        MessagesStorage.Instance.updateEncryptedChat(newChat);
        Utilities.RunOnUIThread(new Runnable() {
            @Override
            public void run() {
                encryptedChats.put(newChat.id, newChat);
                NotificationCenter.Instance.postNotificationName(encryptedChatUpdated, newChat);
            }
        });
        declineSecretChat(encryptedChat.id);
    }
}