Search in sources :

Example 1 with SSHKeyPairI

use of co.krypt.krypton.crypto.SSHKeyPairI in project krypton-android by kryptco.

the class Silo method respondToRequest.

public void respondToRequest(Pairing pairing, Request request, boolean requestAllowed) throws Unrecoverable {
    // Fine-grained locking allows performing signatures in parallel
    synchronized ((Silo.class.getName() + request.requestID).intern()) {
        synchronized (Silo.class) {
            if (sendCachedResponseIfPresent(pairing, request)) {
                return;
            }
        }
        Response response = Response.with(request);
        Analytics analytics = new Analytics(context);
        if (analytics.isDisabled()) {
            response.trackingID = "disabled";
        } else {
            response.trackingID = analytics.getClientID();
        }
        request.body.visit(new RequestBody.Visitor<Void, Unrecoverable>() {

            @Override
            public Void visit(MeRequest meRequest) throws CryptoException {
                response.meResponse = new MeResponse(meStorage.loadWithUserID(meRequest.userID()));
                return null;
            }

            @Override
            public Void visit(SignRequest signRequest) throws Unrecoverable {
                signRequest.validate();
                response.signResponse = new SignResponse();
                if (requestAllowed) {
                    try {
                        SSHKeyPairI key = MeStorage.getOrLoadKeyPair(context);
                        if (MessageDigest.isEqual(signRequest.publicKeyFingerprint, key.publicKeyFingerprint())) {
                            if (signRequest.verifyHostName()) {
                                String hostName = signRequest.hostAuth.hostNames[0];
                                String hostKey = Base64.encodeAsString(signRequest.hostAuth.hostKey);
                                synchronized (databaseLock) {
                                    List<KnownHost> matchingKnownHosts = dbHelper.getKnownHostDao().queryForEq("host_name", hostName);
                                    try {
                                        Sigchain.NativeResult<List<Sigchain.PinnedHost>> teamPinnedHosts = TeamDataProvider.getPinnedKeysByHost(context, hostName);
                                        if (teamPinnedHosts.success != null) {
                                            for (Sigchain.PinnedHost pinnedHost : teamPinnedHosts.success) {
                                                matchingKnownHosts.add(new KnownHost(pinnedHost.host, co.krypt.krypton.crypto.Base64.encode(pinnedHost.publicKey), 0));
                                            }
                                        }
                                    } catch (Native.NotLinked e) {
                                        e.printStackTrace();
                                    }
                                    if (matchingKnownHosts.size() == 0) {
                                        dbHelper.getKnownHostDao().create(new KnownHost(hostName, hostKey, System.currentTimeMillis() / 1000));
                                        broadcastKnownHostsChanged();
                                    } else {
                                        boolean foundKnownHost = false;
                                        List<String> pinnedPublicKeys = new ArrayList<>();
                                        for (KnownHost pinnedHost : matchingKnownHosts) {
                                            pinnedPublicKeys.add(pinnedHost.publicKey);
                                            if (pinnedHost.publicKey.equals(hostKey)) {
                                                foundKnownHost = true;
                                                break;
                                            }
                                        }
                                        if (!foundKnownHost) {
                                            throw new MismatchedHostKeyException(pinnedPublicKeys, "Expected " + pinnedPublicKeys.toString() + " received " + hostKey);
                                        }
                                    }
                                }
                            }
                            String algo = signRequest.algo();
                            if ((key instanceof RSASSHKeyPair) && request.semVer().lessThan(Versions.KR_SUPPORTS_RSA_SHA256_512)) {
                                algo = "ssh-rsa";
                            }
                            response.signResponse.signature = key.signDigestAppendingPubkey(signRequest.data, algo);
                            SSHSignatureLog log = new SSHSignatureLog(signRequest.data, true, signRequest.command, signRequest.user(), signRequest.firstHostnameIfExists(), System.currentTimeMillis() / 1000, signRequest.verifyHostName(), JSON.toJson(signRequest.hostAuth), pairing.getUUIDString(), pairing.workstationName);
                            co.krypt.krypton.team.log.Log teamLog = co.krypt.krypton.team.log.Log.fromSSHRequest(pairing, request, signRequest, co.krypt.krypton.team.log.Log.Body.SSH.Result.signature(response.signResponse.signature));
                            EventBus.getDefault().post(new TeamService.EncryptLog(C.background(context), teamLog));
                            pairingStorage.appendToSSHLog(log);
                            Notifications.notifySuccess(context, pairing, request, log);
                            if (signRequest.verifiedHostNameOrDefault("unknown host").equals("me.krypt.co")) {
                                Intent sshMeIntent = new Intent(TestSSHFragment.SSH_ME_ACTION);
                                LocalBroadcastManager.getInstance(context).sendBroadcast(sshMeIntent);
                            }
                            if (signRequest.hostAuth == null) {
                                new Analytics(context).postEvent("host", "unknown", null, null, false);
                            } else if (!signRequest.verifyHostName()) {
                                new Analytics(context).postEvent("host", "unverified", null, null, false);
                            }
                        } else {
                            Log.e(TAG, Base64.encodeAsString(signRequest.publicKeyFingerprint) + " != " + Base64.encodeAsString(key.publicKeyFingerprint()));
                            response.signResponse.error = "unknown key fingerprint";
                        }
                    } catch (SQLException e) {
                        StringWriter sw = new StringWriter();
                        PrintWriter pw = new PrintWriter(sw);
                        e.printStackTrace(pw);
                        response.signResponse.error = "SQL error: " + e.getMessage() + "\n" + sw.toString();
                        e.printStackTrace();
                    } catch (MismatchedHostKeyException e) {
                        response.signResponse.error = "host public key mismatched";
                        if (signRequest.hostAuth.hostKey != null) {
                            co.krypt.krypton.team.log.Log teamLog = co.krypt.krypton.team.log.Log.fromSSHRequest(pairing, request, signRequest, co.krypt.krypton.team.log.Log.Body.SSH.Result.hostMismatch(e.pinnedPublicKeys.toArray(new String[] {})));
                            EventBus.getDefault().post(new TeamService.EncryptLog(C.background(context), teamLog));
                        }
                        Notifications.notifyReject(context, pairing, request, "Host public key mismatched.");
                        e.printStackTrace();
                    }
                } else {
                    response.signResponse.error = "rejected";
                    co.krypt.krypton.team.log.Log teamLog = co.krypt.krypton.team.log.Log.fromSSHRequest(pairing, request, signRequest, co.krypt.krypton.team.log.Log.Body.SSH.Result.userRejected());
                    EventBus.getDefault().post(new TeamService.EncryptLog(C.background(context), teamLog));
                    pairingStorage.appendToSSHLog(new SSHSignatureLog(signRequest.data, false, signRequest.command, signRequest.user(), signRequest.firstHostnameIfExists(), System.currentTimeMillis() / 1000, signRequest.verifyHostName(), JSON.toJson(signRequest.hostAuth), pairing.getUUIDString(), pairing.workstationName));
                }
                return null;
            }

            @Override
            public Void visit(GitSignRequest gitSignRequest) throws Unrecoverable {
                if (requestAllowed) {
                    try {
                        SSHKeyPairI key = MeStorage.getOrLoadKeyPair(context);
                        new MeStorage(context).loadWithUserID(UserID.parse(gitSignRequest.userID));
                        co.krypt.krypton.team.log.Log.Body.GitSignatureResult gitSignatureResult = new co.krypt.krypton.team.log.Log.Body.GitSignatureResult();
                        co.krypt.krypton.log.Log log = gitSignRequest.body.visit(new GitSignRequestBody.Visitor<co.krypt.krypton.log.Log, Exception>() {

                            @Override
                            public co.krypt.krypton.log.Log visit(CommitInfo commit) throws Unrecoverable {
                                byte[] signature = SignableUtils.signBinaryDocument(commit, key, HashAlgorithm.SHA512);
                                response.gitSignResponse = new GitSignResponse(signature, null);
                                gitSignatureResult.signature = signature;
                                GitCommitSignatureLog commitLog = new GitCommitSignatureLog(pairing, commit, new AsciiArmor(AsciiArmor.HeaderLine.SIGNATURE, AsciiArmor.backwardsCompatibleHeaders(request.semVer()), signature).toString());
                                pairings().appendToCommitLogs(commitLog);
                                return commitLog;
                            }

                            @Override
                            public co.krypt.krypton.log.Log visit(TagInfo tag) throws Unrecoverable {
                                byte[] signature = SignableUtils.signBinaryDocument(tag, key, HashAlgorithm.SHA512);
                                response.gitSignResponse = new GitSignResponse(signature, null);
                                gitSignatureResult.signature = signature;
                                GitTagSignatureLog tagLog = new GitTagSignatureLog(pairing, tag, new AsciiArmor(AsciiArmor.HeaderLine.SIGNATURE, AsciiArmor.backwardsCompatibleHeaders(request.semVer()), signature).toString());
                                pairings().appendToTagLogs(tagLog);
                                return tagLog;
                            }
                        });
                        co.krypt.krypton.team.log.Log teamLog = co.krypt.krypton.team.log.Log.fromGitRequest(pairing, request, gitSignRequest, gitSignatureResult);
                        EventBus.getDefault().post(new TeamService.EncryptLog(C.background(context), teamLog));
                        Notifications.notifySuccess(context, pairing, request, log);
                    } catch (Exception e) {
                        e.printStackTrace();
                        response.gitSignResponse = new GitSignResponse(null, "unknown error");
                    }
                } else {
                    response.gitSignResponse = new GitSignResponse(null, "rejected");
                    gitSignRequest.body.visit(new GitSignRequestBody.Visitor<Void, RuntimeException>() {

                        @Override
                        public Void visit(CommitInfo commit) throws RuntimeException {
                            pairings().appendToCommitLogs(new GitCommitSignatureLog(pairing, commit, null));
                            return null;
                        }

                        @Override
                        public Void visit(TagInfo tag) throws RuntimeException {
                            pairings().appendToTagLogs(new GitTagSignatureLog(pairing, tag, null));
                            return null;
                        }
                    });
                    co.krypt.krypton.team.log.Log teamLog = co.krypt.krypton.team.log.Log.fromGitRequest(pairing, request, gitSignRequest, co.krypt.krypton.team.log.Log.Body.GitSignatureResult.userRejected());
                    EventBus.getDefault().post(new TeamService.EncryptLog(C.background(context), teamLog));
                }
                return null;
            }

            @Override
            public Void visit(UnpairRequest unpairRequest) throws Unrecoverable {
                // Processed in handle()
                return null;
            }

            @Override
            public Void visit(HostsRequest hostsRequest) throws Unrecoverable {
                HostsResponse hostsResponse = new HostsResponse();
                synchronized (databaseLock) {
                    try {
                        List<SSHSignatureLog> sshLogs = dbHelper.getSSHSignatureLogDao().queryBuilder().groupByRaw("user, host_name").query();
                        List<UserAndHost> userAndHosts = new LinkedList<>();
                        for (SSHSignatureLog log : sshLogs) {
                            UserAndHost userAndHost = new UserAndHost();
                            userAndHost.user = log.user;
                            userAndHost.host = log.hostName;
                            userAndHosts.add(userAndHost);
                        }
                        HostInfo hostInfo = new HostInfo();
                        UserAndHost[] userAndHostsArray = new UserAndHost[userAndHosts.size()];
                        userAndHosts.toArray(userAndHostsArray);
                        hostInfo.hosts = userAndHostsArray;
                        List<UserID> userIDs = meStorage.getUserIDs();
                        List<String> userIDStrings = new LinkedList<>();
                        for (UserID userID : userIDs) {
                            userIDStrings.add(userID.toString());
                        }
                        String[] userIDArray = new String[userIDs.size()];
                        userIDStrings.toArray(userIDArray);
                        hostInfo.pgpUserIDs = userIDArray;
                        hostsResponse.hostInfo = hostInfo;
                    } catch (SQLException e1) {
                        hostsResponse.error = "sql exception";
                    }
                }
                response.hostsResponse = hostsResponse;
                return null;
            }

            @Override
            public Void visit(ReadTeamRequest readTeamRequest) throws Unrecoverable {
                SuccessOrTaggedErrorResult<JsonObject> result = new SuccessOrTaggedErrorResult<>();
                response.readTeamResponse = result;
                if (requestAllowed) {
                    try {
                        Sigchain.NativeResult<JsonObject> readToken = TeamDataProvider.signReadToken(context, readTeamRequest.publicKey);
                        if (readToken.success != null) {
                            result.success = readToken.success;
                        } else {
                            result.error = readToken.error;
                        }
                    } catch (Native.NotLinked e) {
                        e.printStackTrace();
                        result.error = e.getMessage();
                    }
                } else {
                    response.readTeamResponse.error = "rejected";
                }
                return null;
            }

            @Override
            public Void visit(LogDecryptionRequest logDecryptionRequest) throws Unrecoverable {
                SuccessOrTaggedErrorResult<JsonObject> result = new SuccessOrTaggedErrorResult<>();
                response.logDecryptionResponse = result;
                if (requestAllowed) {
                    try {
                        Sigchain.NativeResult<JsonObject> unwrappedKey = TeamDataProvider.unwrapKey(context, logDecryptionRequest.wrappedKey);
                        if (unwrappedKey.success != null) {
                            result.success = unwrappedKey.success;
                        } else {
                            result.error = unwrappedKey.error;
                        }
                    } catch (Native.NotLinked e) {
                        e.printStackTrace();
                        result.error = e.getMessage();
                    }
                } else {
                    response.logDecryptionResponse.error = "rejected";
                }
                return null;
            }

            @Override
            public Void visit(TeamOperationRequest teamOperationRequest) throws Unrecoverable {
                SuccessOrTaggedErrorResult<Sigchain.TeamOperationResponse> result = new SuccessOrTaggedErrorResult<>();
                response.teamOperationResponse = result;
                if (requestAllowed) {
                    try {
                        Sigchain.NativeResult<Sigchain.TeamOperationResponse> nativeResult = TeamDataProvider.requestTeamOperation(context, teamOperationRequest.operation);
                        if (nativeResult.success != null) {
                            response.teamOperationResponse.success = nativeResult.success;
                        } else {
                            response.teamOperationResponse.error = nativeResult.error;
                        }
                    } catch (Native.NotLinked e) {
                        e.printStackTrace();
                        result.error = e.getMessage();
                    }
                } else {
                    response.teamOperationResponse.error = "rejected";
                }
                return null;
            }
        });
        response.snsEndpointARN = SNSTransport.getInstance(context).getEndpointARN();
        synchronized (Silo.class) {
            try {
                if (responseDiskCacheByRequestID != null && !responseDiskCacheByRequestID.isClosed()) {
                    DiskLruCache.Editor cacheEditor = responseDiskCacheByRequestID.edit(request.requestIDCacheKey(pairing));
                    cacheEditor.set(0, JSON.toJson(response));
                    cacheEditor.commit();
                    responseDiskCacheByRequestID.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new Unrecoverable(e);
            }
            responseMemCacheByRequestID.put(request.requestIDCacheKey(pairing), response);
        }
        send(pairing, response);
    }
}
Also used : GitTagSignatureLog(co.krypt.krypton.log.GitTagSignatureLog) TeamOperationRequest(co.krypt.krypton.protocol.TeamOperationRequest) SSHKeyPairI(co.krypt.krypton.crypto.SSHKeyPairI) KnownHost(co.krypt.krypton.knownhosts.KnownHost) DiskLruCache(com.jakewharton.disklrucache.DiskLruCache) TagInfo(co.krypt.krypton.git.TagInfo) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) GitTagSignatureLog(co.krypt.krypton.log.GitTagSignatureLog) Log(android.util.Log) GitCommitSignatureLog(co.krypt.krypton.log.GitCommitSignatureLog) SSHSignatureLog(co.krypt.krypton.log.SSHSignatureLog) HostsRequest(co.krypt.krypton.protocol.HostsRequest) MeResponse(co.krypt.krypton.protocol.MeResponse) LogDecryptionRequest(co.krypt.krypton.protocol.LogDecryptionRequest) UserAndHost(co.krypt.krypton.protocol.UserAndHost) TeamService(co.krypt.krypton.team.TeamService) MismatchedHostKeyException(co.krypt.krypton.exception.MismatchedHostKeyException) HostsResponse(co.krypt.krypton.protocol.HostsResponse) MeRequest(co.krypt.krypton.protocol.MeRequest) SQLException(java.sql.SQLException) GitCommitSignatureLog(co.krypt.krypton.log.GitCommitSignatureLog) Unrecoverable(co.krypt.krypton.exception.Unrecoverable) AsciiArmor(co.krypt.krypton.pgp.asciiarmor.AsciiArmor) StringWriter(java.io.StringWriter) GitSignResponse(co.krypt.krypton.protocol.GitSignResponse) SignResponse(co.krypt.krypton.protocol.SignResponse) GitSignRequest(co.krypt.krypton.protocol.GitSignRequest) UserID(co.krypt.krypton.pgp.UserID) CommitInfo(co.krypt.krypton.git.CommitInfo) RequestBody(co.krypt.krypton.protocol.RequestBody) GitSignRequestBody(co.krypt.krypton.protocol.GitSignRequestBody) RequestBody(co.krypt.krypton.protocol.RequestBody) GitSignRequestBody(co.krypt.krypton.protocol.GitSignRequestBody) PrintWriter(java.io.PrintWriter) SuccessOrTaggedErrorResult(co.krypt.krypton.protocol.SuccessOrTaggedErrorResult) RSASSHKeyPair(co.krypt.krypton.crypto.RSASSHKeyPair) SignRequest(co.krypt.krypton.protocol.SignRequest) GitSignRequest(co.krypt.krypton.protocol.GitSignRequest) Sigchain(co.krypt.krypton.team.Sigchain) Intent(android.content.Intent) UnpairRequest(co.krypt.krypton.protocol.UnpairRequest) IOException(java.io.IOException) GitSignResponse(co.krypt.krypton.protocol.GitSignResponse) Analytics(co.krypt.krypton.analytics.Analytics) CryptoException(co.krypt.krypton.exception.CryptoException) TransportException(co.krypt.krypton.exception.TransportException) ProtocolException(co.krypt.krypton.exception.ProtocolException) SQLException(java.sql.SQLException) MismatchedHostKeyException(co.krypt.krypton.exception.MismatchedHostKeyException) IOException(java.io.IOException) HostsResponse(co.krypt.krypton.protocol.HostsResponse) GitSignResponse(co.krypt.krypton.protocol.GitSignResponse) MeResponse(co.krypt.krypton.protocol.MeResponse) SignResponse(co.krypt.krypton.protocol.SignResponse) UnpairResponse(co.krypt.krypton.protocol.UnpairResponse) AckResponse(co.krypt.krypton.protocol.AckResponse) Response(co.krypt.krypton.protocol.Response) ReadTeamRequest(co.krypt.krypton.protocol.ReadTeamRequest) SSHSignatureLog(co.krypt.krypton.log.SSHSignatureLog) MeStorage(co.krypt.krypton.me.MeStorage) CryptoException(co.krypt.krypton.exception.CryptoException) HostInfo(co.krypt.krypton.protocol.HostInfo)

Example 2 with SSHKeyPairI

use of co.krypt.krypton.crypto.SSHKeyPairI in project krypton-android by kryptco.

the class MeStorage method loadWithUserID.

public Profile loadWithUserID(@Nullable UserID userID) {
    synchronized (lock) {
        String meJSON = preferences.getString("ME", null);
        if (meJSON == null) {
            Log.i(TAG, "no profile found");
            return null;
        }
        Profile me = JSON.fromJson(meJSON, Profile.class);
        if (me == null) {
            Log.i(TAG, "no profile found");
            return null;
        }
        try {
            SSHKeyPairI kp = getOrLoadKeyPair(context);
            if (kp != null) {
                me.sshWirePublicKey = kp.publicKeySSHWireFormat();
                if (userID != null) {
                    try {
                        List<UserID> userIDs = getUserIDs();
                        // keep USER_ID_LIMIT most recent UserIDs
                        if (userIDs.remove(userID)) {
                            userIDs.add(userID);
                        } else {
                            if (userIDs.size() >= USER_ID_LIMIT) {
                                userIDs.remove(0);
                            }
                            userIDs.add(userID);
                            PGPPublicKey pgpPublicKey = PGPManager.publicKeyWithIdentities(kp, userIDs);
                            me.pgpPublicKey = pgpPublicKey.serializedBytes();
                            if (userIDs.size() == USER_ID_LIMIT) {
                                // detect abuse of exporting PGP userIDs
                                Notifications.notifyPGPKeyExport(context, pgpPublicKey);
                            }
                        }
                        set(me, userIDs);
                    } catch (PGPException | IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (InvalidKeyException | IOException | CryptoException e) {
            e.printStackTrace();
        }
        try {
            me.teamCheckpoint = TeamDataProvider.getTeamCheckpoint(context).success;
        } catch (Native.NotLinked notLinked) {
            notLinked.printStackTrace();
        }
        return me;
    }
}
Also used : SSHKeyPairI(co.krypt.krypton.crypto.SSHKeyPairI) PGPPublicKey(co.krypt.krypton.pgp.PGPPublicKey) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) Profile(co.krypt.krypton.protocol.Profile) PGPException(co.krypt.krypton.pgp.PGPException) Native(co.krypt.krypton.team.Native) UserID(co.krypt.krypton.pgp.UserID) CryptoException(co.krypt.krypton.exception.CryptoException)

Example 3 with SSHKeyPairI

use of co.krypt.krypton.crypto.SSHKeyPairI in project krypton-android by kryptco.

the class KeyManagerInstrumentedTest method keyGenerationAndDeletion_succeed.

@Test
public void keyGenerationAndDeletion_succeed() throws Exception {
    final Context context = InstrumentationRegistry.getTargetContext();
    for (KeyType type : SUPPORTED_KEY_TYPES) {
        KeyManager.deleteKeyPair(context, type, "test");
        SSHKeyPairI kp1 = KeyManager.loadOrGenerateKeyPair(InstrumentationRegistry.getTargetContext(), type, "test");
        Log.i("TEST", kp1.publicKeyDERBase64());
        KeyManager.deleteKeyPair(context, type, "test");
    }
}
Also used : Context(android.content.Context) KeyType(co.krypt.krypton.crypto.KeyType) SSHKeyPairI(co.krypt.krypton.crypto.SSHKeyPairI) Test(org.junit.Test)

Example 4 with SSHKeyPairI

use of co.krypt.krypton.crypto.SSHKeyPairI in project krypton-android by kryptco.

the class PGPCodesignTest method dataSigning_succeeds.

@Test
public void dataSigning_succeeds() throws Exception {
    final byte[] data = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
    SSHKeyPairI kp1 = KeyManager.loadOrGenerateKeyPair(InstrumentationRegistry.getTargetContext(), KeyType.RSA, "test");
    PGPPublicKey pubkey = new PGPPublicKey(kp1, Collections.singletonList(new UserID("Kevin King", "kevin@krypt.co")));
    UnsignedBinaryDocument unsigned = new UnsignedBinaryDocument(data, kp1, HashAlgorithm.SHA512);
    SignedSignatureAttributes sig = unsigned.sign(kp1.pgpSign(HashAlgorithm.SHA512, SignableUtils.signableBytes(unsigned)));
    byte[] serializedSig = sig.serializedBytes();
    SignedSignatureAttributes parsedSig = SignedSignatureAttributes.parse(new DataInputStream(new ByteArrayInputStream(serializedSig)));
    Assert.assertTrue(parsedSig.attributes.attributes.hashAlgorithm == HashAlgorithm.SHA512);
    Assert.assertTrue(parsedSig.attributes.attributes.pkAlgorithm == PublicKeyAlgorithm.RSA_SIGN_ONLY);
    Assert.assertTrue(parsedSig.attributes.attributes.type == SignatureType.BINARY);
    Assert.assertFalse(parsedSig.attributes.attributes.unhashedSubpackets.issuer.header.type.critical);
}
Also used : UnsignedBinaryDocument(co.krypt.krypton.pgp.codesign.UnsignedBinaryDocument) ByteArrayInputStream(java.io.ByteArrayInputStream) UserID(co.krypt.krypton.pgp.UserID) SignedSignatureAttributes(co.krypt.krypton.pgp.packet.SignedSignatureAttributes) SSHKeyPairI(co.krypt.krypton.crypto.SSHKeyPairI) PGPPublicKey(co.krypt.krypton.pgp.PGPPublicKey) DataInputStream(java.io.DataInputStream) Test(org.junit.Test)

Example 5 with SSHKeyPairI

use of co.krypt.krypton.crypto.SSHKeyPairI in project krypton-android by kryptco.

the class GenerateFragment method next.

private void next() {
    KeyType keyType = null;
    if (keyTypeButton.getText().equals(getString(R.string.ed25519_key_type))) {
        keyType = KeyType.Ed25519;
    } else if (keyTypeButton.getText().equals(getString(R.string.rsa_key_type))) {
        keyType = KeyType.RSA;
    } else {
        keyType = KeyType.RSA;
    }
    final KeyType finalKeyType = keyType;
    final FragmentActivity context = getActivity();
    final OnboardingProgress progress = new OnboardingProgress(getContext());
    progress.setStage(OnboardingStage.GENERATING);
    new Analytics(context).postEvent("onboard", "generate tapped", null, null, false);
    final long startMillis = System.currentTimeMillis();
    final GeneratingFragment generatingFragment = new GeneratingFragment();
    getActivity().getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left).replace(R.id.activity_onboarding, generatingFragment).commit();
    final Fragment self = this;
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                final long start = System.currentTimeMillis();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                SSHKeyPairI pair = KeyManager.loadOrGenerateKeyPair(context, finalKeyType, KeyManager.ME_TAG);
                new MeStorage(context).set(new Profile("", pair.publicKeySSHWireFormat(), null, null));
                final long genTime = System.currentTimeMillis() - start;
                new Analytics(context).postEvent("keypair", "generate", null, (int) (genTime / 1000), false);
                if (genTime < 5000) {
                    try {
                        Thread.sleep(5000 - genTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                generatingFragment.onGenerate();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                progress.setStage(OnboardingStage.ENTER_EMAIL);
                EnterEmailFragment enterEmailFragment = new EnterEmailFragment();
                final FragmentActivity activity = context;
                if (activity != null && !activity.isDestroyed() && !activity.isFinishing()) {
                    activity.getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left).hide(generatingFragment).add(R.id.activity_onboarding, enterEmailFragment).show(enterEmailFragment).commitAllowingStateLoss();
                }
            } catch (InvalidKeyException | IOException | CryptoException | UnsupportedOperationException | IllegalArgumentException e) {
                e.printStackTrace();
                progress.reset();
                final FragmentActivity activity = context;
                if (activity != null && !activity.isDestroyed() && !activity.isFinishing()) {
                    GenerateFragment generateFragment = new GenerateFragment();
                    if (finalKeyType == KeyType.RSA) {
                        Bundle args = new Bundle();
                        args.putString(DEFAULT_KEY_TYPE_KEY, activity.getString(R.string.ed25519_key_type));
                        generateFragment.setArguments(args);
                        activity.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(activity, "Error generating rsa key, try again to generate an ed25519 key.", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                    activity.getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left).replace(R.id.activity_onboarding, generateFragment).commitAllowingStateLoss();
                }
            }
        }
    }).start();
}
Also used : KeyType(co.krypt.krypton.crypto.KeyType) Bundle(android.os.Bundle) SSHKeyPairI(co.krypt.krypton.crypto.SSHKeyPairI) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) Fragment(android.support.v4.app.Fragment) Analytics(co.krypt.krypton.analytics.Analytics) Profile(co.krypt.krypton.protocol.Profile) FragmentActivity(android.support.v4.app.FragmentActivity) MeStorage(co.krypt.krypton.me.MeStorage) CryptoException(co.krypt.krypton.exception.CryptoException)

Aggregations

SSHKeyPairI (co.krypt.krypton.crypto.SSHKeyPairI)9 KeyType (co.krypt.krypton.crypto.KeyType)6 Test (org.junit.Test)6 Context (android.content.Context)4 UserID (co.krypt.krypton.pgp.UserID)4 CryptoException (co.krypt.krypton.exception.CryptoException)3 PGPPublicKey (co.krypt.krypton.pgp.PGPPublicKey)3 IOException (java.io.IOException)3 Analytics (co.krypt.krypton.analytics.Analytics)2 RSAKeyManager (co.krypt.krypton.crypto.RSAKeyManager)2 MeStorage (co.krypt.krypton.me.MeStorage)2 Profile (co.krypt.krypton.protocol.Profile)2 Intent (android.content.Intent)1 Bundle (android.os.Bundle)1 Fragment (android.support.v4.app.Fragment)1 FragmentActivity (android.support.v4.app.FragmentActivity)1 Log (android.util.Log)1 RSASSHKeyPair (co.krypt.krypton.crypto.RSASSHKeyPair)1 MismatchedHostKeyException (co.krypt.krypton.exception.MismatchedHostKeyException)1 ProtocolException (co.krypt.krypton.exception.ProtocolException)1