Planning

Intro

Design flaws are as bad as programming bugs: Both are vulnerabilities an attacker can abuse.

A software or hardware design well done can simplify programming and strongly improve security.

Many specific technologies require domain knowledge to be used in a secure fashion. For example a crypto library offers an API to be used by programmers without having them understand the maths. This API can be simple and fool-proof or built-for-experts with lots of ways to make horrible mistakes. In the last case you will require lots of domain knowledge to build a secure application.

This chapter will extend principles from the background chapter into technology specific knowledge.

Updates

As soon as your system reaches a certain level of complexity, you will require updates. Reason for that are the inevitable bugs and feature requests.

And as bugs can be vulnerabilities you will not be offering a secure solution without updates.

The software offered today is highly complex. Caused by the foundation that is used: Operating Systems, libraries, frameworks, …

Even CPU microcode can be updated.

Updates are the solution. And they add more complexity.

Things that a good update strategy covers

  • Be able to rollback
  • Verify signature
  • Secure key handling
  • Verify version - only upgrade and no downgrades
  • Track distribution
  • Be able to stop update roll outs
  • Distributing the updates
  • Compress updates
  • Diff updates
  • Incentives to update
  • Automatic updates

Things to avoid

  • TOCTTOU Time of check to time of use - error
  • Break the update chain

Especially breaking the update chain (for example by ruining the update on the client system) is one of the biggest fears.

Response Time

This is the time you have to response to an incident. Normally it is the span between learning about an issue and successfully updating all your customers systems.

If a vulnerability gets known to the bad guys, expect a time-to-exploit of a few days. Normal process is that someone identifies the vulnerability and writes an exploit (plus a blog post). The exploit is then stabilized and integrated into attack systems (metasploit for the more white hack side, exploit kits for the bad guys).

If a vulnerability gets reported as “responsible disclosure” by a friendly hacker you will have about 90 days (standard) to release the fix to all customers. If you have good reasons (complex situation where it is hard to get all your users updated) you can maybe negotiate and get some more days. But there is a very good reason for the 90 days: It is a reasonable time to get the fix released and a longer time frame would increase the risk that a bad guy finds the same vulnerability in parallel. This happened more often than you think.

Short: You will not be able to ship the fixes with the next regular update. Be ready to for quick response. Build your processes from support call to all-your-users update accordingly.

One more thing: As soon as the first client gets an update, the bad guys could get it as well. Normally they do a binary diff (using disassembly tools). From that diff they can learn which vulnerability you just patched. The race is on between the bad guys creating a reliable exploit and you getting the update to your last customer.

These disassembler tools may sound arcane, but are quite simple to find and sophisticated.

  • IDA, paid and free test version. For Mac/Win/Linux
  • Hopper, Mac/Linux. Test version available
  • Radare2, Mac/Windows/Linux/… %% TODO Add Ghidra

Update strategy details

Be able to rollback

Be able to roll back your changes either automatically or by user interaction if the update breaks something. User interaction could be “press the reset button for 10 seconds”. Rollback could be to the factory system or last-know-good software state. This will reduce your stress when doing emergency updates.

Verify signature

Cryptographically sign your binaries (public key cryptography is the keyword).

One way of signing your binaries is to create at least a sha256 hash of your binaries (md5, CRC and sha1 are broken). Create a update config file containing all your files, their versions and their hashes. This update config file should also have a unique version number that is incremented only.

Now sign this config file using public key signatures.

This config file will be checked against the public key file on the end-system. If the key matches and the version is bigger than the current one the binaries can be downloaded and verified against the hashes.

Secure key handling

The secret key must be stored on an isolated system. Not a build machine and especially not the download server. You sign the update binary or config config prior to release with this key.

You will want a second emergency key (its public part also distributed to the clients). This one is stored in a safe. If the first key is compromised you can can revoke it and do an emergency update now binding the emergency key to the clients.

Verify version - only upgrade

Only update to a newer version. No updates to older versions. If you ever want to roll back a change, release an old version of your programs with a higher version number.

The reason for this is that an attacker could trick clients to install updates with older versions of your program that still contains known vulnerabilities. And hack the systems afterwards.

Track distribution

You want to track your update roll out. And if systems are functional post-update. Especially that.

Be able to stop updates

If you roll out a broken update, you should be able to remove it from your update servers very quick. That way other users do not risk ruining their systems. Automatic roll back (mentioned a few chapters above) will take care for the updated systems.

Slowly increasing the percentage of client systems getting the update offered is also part of this. Start with a few percent, measure success, increase percentage.

Result of these precautions is that everyone (including management) feels much more comfortable rolling out updates. And this will make it simpler to update clients with a new version that contains “only one security fix that is not even abused - as far as we know”.

Distributing the updates

If your updates are big your servers will not have enough bandwidth for to update all clients in time. You could use a CDN for your updates. To further reduce load update in stages:

  1. Check first if there is a newer version than the one installed. This is a few bytes only
  2. Download config file. Verify it.
  3. Download binaries

As you have your files signed, an option to be protected against DDOS-es vs. your update infrastructure would be to also have a fallback to a peer-to-peer network (BitTorrent). Some bigger software applications (games) use BitTorrent. Do not make that the only source ! BitTorrent could be blocked in some environments like companies. Also do not waste the users bandwidth without asking. It could be expensive for some of them if they are connected using a mobile network.

Compress updates

Compressing updates reduces stress on your update servers and makes them more resilient against DDOS attacks. Test common algorithms with your update files. The algorithms have different strengths and weaknesses. Also: De-compressing is very often much faster than compressing. And this is what your clients are doing.

Diff updates

If you are shipping large updates, you want to ship them as diffs to previous versions. Depending on your file types there can be different diff algorithms that are quite effective. Please test before using. For PE files there is “courgette”. Always verify after diffing if the created file is the proper one (by hash). If something went wrong, fall back to whole-file download.

That way there is no additional risk.

Incentives

Some users care more about new Emojis than about vulnerability fixes. Maybe bundle some eye candy (new backgrounds, …) with the updates to get the users to update. Sad but true.

Plan for several channels

When creating an updater be ready to add new channels later. Valuable channels to have are for example an “internal” and a “beta” channel.

Automatic updates

Do updates in the background. Without user interaction. Especially if you have corporate users offer an Opt-out hidden in some config. Companies want to test before they deploy to thousands of users.

If the update requires a restart of the software think about waiting for the user to naturally restart it - with a timer. If the user does not restart it after X days nudge him.

Control the update infrastructure

It is essential that you control your update infrastructure. There are several things that can break given time:

  • certificates run out
  • You lose ownership of your domain
  • server needs system updates

Plan ahead and create scripts that test your current situation and warn you weeks ahead before your domain ownership runs out or before you should create a new certificate.

Another thing to control is the certificate that signs the updates. It must not be on the update server. It also should not be on the build server (where lots of people from you company can access it) but on a dedicated system.

Details for things to avoid

TOCTTOU Time of check to time of use - error

Wikipedia on TOCTOU

A possible issue when checking the signature of an update package: If the package is on an external medium and the updater is not copying it locally, the attacker can switch the (legit) package after verification with a malicious package.

  1. You verify the (clean) external data’s signature
  2. Attacker replaces clean software with malicious software
  3. Your tool now installs the malicious software from external medium

Solution: Copy the package into a local storage before verification and installation.

Break the update chain

Never break the update chain for your devices. As long as updates work you can fix anything. Focus of your testers should be to (automatically) test updates over several versions.

Passwords

Passwords are one of the most common authentication technologies.

There are different kinds of passwords: Pins, Passwords and Passphrases.

PINs

Pins are short (4-10), contain most often only numbers and are insecure. To still make them a valid security feature add a short delay in between pins entered. After the 3rd wrong entry either lock the system and request a special PIN (like PUK for a Smartphone SIM cards) or add a massive penalty (1 minute) which increases during the next wrong entries. A negative side effect of this is that the system can be locked by a malicious actor…

Passwords

Passwords are longer than PINs. As with the current state of technology (cloud computing and GPUs) standard passwords have to be long to have a decent amount of security. To improve the situation you can push the user to create good passwords (high entropy thanks to a large character set, avoiding the top 100+ passwords, …)

Passphrases

Intentionally long passwords. If you create your product for a situation where a good keyboard is available or passwords are stored in password stores you should aim for that - or just do not artificially restrict password length and nudge users to use long passwords in a friendly way.

Entropy matters

Help the user to choose high-entropy passwords. Depending on the system the user is using there are several different approaches to generate high entropy passwords. Smartphone keyboards for example make it very difficult to enter special characters. Maybe go for long passphrases instead ? Also: Avoid the most common top 100+ passwords (google for them). Have a list in your app and block list them. Notify the user not to use those. If you have international users you should also have international top 100+ lists.

There is one exception where it is wise to use common passwords like “12345” or “password”: One time accounts without personal data attached. Things that can be stolen without pain to the user. But as a normal user will not be able to make this distinction - do not tell them that there is a situation when weak passwords are OK…

High entropy is based on length of the password and potential character set being used. This is why so many pages push people to have at least

  • Lower case
  • Upper case
  • Special character
  • A Number

In the password. As the code is simple to guarantee at least one of each is in the password it is done that way.

One example of password entropy is the famous Correct horse battery staple

Password hints

Don’t

Users will use them and enter some easy to research data.

Preventing copy & paste

Some developers had the idea to prevent copy & paste. Hoping that can prevent malware from accessing the password in the clipboard.

Maybe that was true. But current malware has many other tricks in addition. If malware is running on the system, it is game over.

The side effect of preventing copy & paste is that people will use shorter and simple passwords because their password stores will not work properly with your password entry.

And password cracking got a lot better thanks to improved computing power.

TL;DR: Do not block copy and paste

Forgot password

While creating an account enforce and verify a link to a mail address. This mail account is your “Trust Anchor” if the user forgets the password. Create a reset link and mail the user. Make sure not to spam the user. Do not revoke the old password until a new one is set.

Do not send a random password by mail but a (randomly generated) link to a page you have to set a new password.

TTL for passwords

If you force the user to renew the password regularly, store a hash of the last 3 passwords the user used and make sure they are not recycled.

Autofill trap

If you create a web page with a password form: Do not allow autofill without user interaction on your web-page password pages.

Malicious Ads are currently creating invisible forms to steal those passwords.

Princeton research

Stolen passwords

Malicious actors are hacking databases and extract the passwords from there. As users have the tendency to use the same password for different accounts this is troubling.

The project HaveIBeenPwned is collecting those stolen databases from the dark web and makes it searchable for your own credentials.

Hashes from there, cracked to 99%: Hash leaks

Besides locking down your database server you should also “hash and salt” the passwords you store. That way you prevent damage in case of a stolen database..

There are special passwords hashing algorithms that can be used.

Cracking passwords

The technology to crack passwords is quite advanced. Besides Rainbow tables, GPU based passwords cracking and Cloud Computing an old tool is word lists:

GPUs

With powerful GPUs and usable APIs available people started to use a cluster of those GPUs to crack hashes (later they shifted to Bitcoins).

This did beat the cracking capabilities of a CPU by a large factor. But people who invested into that had to specialize and offer hash cracking as a service to others. Reason for that is the investment into a bunch of the most powerful GPUs available (and re-investment a few GPU generations later).

Cloud

Cloud computing offers processing power at a discount (especially when going for the compute-spot market). Using thousands of Amazon VMs in parallel to crack some hashes can be the fastest and cheapest way. Investment into GPUs declined and people switch to cloud way of hash cracking.

Rainbow tables

Rainbow tables are attacker tools you should know about.

To crack hashes (and passwords are stored as hashes) attackers use Rainbow Tables. These are large databases with pre-compiled string->hash pairs. That way the attacker invests in storage, but reduces CPU power. If the attacker gets a large database dump with lots of Hashes, it is more efficient to match those two databases once and extract as many matching passwords as possible.

And this is just the Rainbow Table basics. Some more optimization is available.

Relevant for the defender: The attacker just reduced required CPU power and swapped it for HDD space requirements. Common passwords will be in this table and are easy to crack. Non-common passwords or salted passwords are better protected.

Word lists

Attackers use word lists to brute force passwords. It is more effective to use existing words and permutes them than to generate all potential character combinations.

Word lists are available online

Cracking Archive files

Multi threaded password brute forcing for archives: RARCrack %% rarcrack –threads 12 –type zip crypted.zip

Cracking with wordlists:

1 fcrackzip -u -D -p simple_wordlist.txt test_abc.zip

Web site scraping for wordlists

CEWL

Cewl example:

1 sudo apt install cewl
2 cewl -d 2 -m 5 -w docswords.txt https://example.com

Keyloggers

Keyloggers exist as hardware and as software variants. Hardware variants are USB dongles attached between keyboard and computer - external and internal. They record keystrokes and are later collected. Some even have WiFi - reducing the risk for the attacker. Those things are simple and can be deployed by cleaning staff.

Software Keyloggers are drivers installed on the OS. Quite often by malware. They log keys and send their data to the mother ship.

One way to defeat Keyloggers are on-screen keyboards. But at least for the software Keyloggers they fail. Those programs do screenshots as well as logging the physical keyboard.

The positive effect of on-screen keyboards is limited. Please think twice if it is the proper solution for your specific security problem or if it is just security theater.

IoT: Initial passwords

Especially IoT devices and Routers have initial passwords. Some important wisdom:

  • Force the user to change that on first use
  • Do never derive it from MAC address or other system specific number
    • No fancy maths will protect you if you do. And MAC is broadcasted on WiFi
  • Do not use a increment in the factory to initialise the first password
    • Add proper randomness instead

Salting

A salt is a random string/number.

This is added to the password, before it is hashed. The salt is stored together with the username and password-hash in the database - plain text.

By adding a random string/number to the password the user entered before it is hashed, we force the attacker to create a rainbow table for each of these salts.

Create a new random salt for every user. That way even if two users use the same standard password, the resulting hashes will be different.

Make the salt big.

Pepper

Pepper is similar to salt. But pepper is either stored in a different database or in a different configuration file - both the password database and the configuration file have to be hacked.

Or even not stored at all but is small. And then you brute force them when matching passwords to the database. When comparing the hash the computer will have to generate lots of hashes with password + all possible peppers.

You can afford the extra computing power - while the attacker trying to hack millions of your accounts can not.

Beyond passwords: “Two-factor authentication”

Technology that extends passwords is already a part of many products. In addition to passwords so called “two-factor authentication” is implemented.

A second factor - and a second communication channel - is required. This improves security.

The second factor is very often based on a hardware device.

Two major concepts are existing.

Time-based One-Time Password (TOTP)

The user has a device that shared an initial secret with the server. Based on this secret and the current time a short lived number is generated. The user enters this number in addition to the normal password to access the server. To verify the server just calculates the same data using the current time and the shared secret.

For the user it looks like an App on the smartphone that generates a 6 digit code. A countdown shows its validity (30 seconds are recommended in the RFC).

The best known app for that is the Google Authenticator

RFC 6238

Universal Two-Factor (U2F)

U2F uses a device with a asymmetric crypto implementation. It can export the public key and sign challenges with the private key - which is sealed inside of the device.

The public key is registered at the server. The best known device for U2F is the Yubikey which looks like a USB memory stick. But it can also offer NFC to be used with mobile phones.

FIDO U2F

Yubikey

Backup codes

As mobile phones tend to fall into a toilette or get lost somewhere else your backend will have to offer backup codes as well. Those are generated when the device is paired and can either be stored by the user or printed and locked away.

Those codes should be valid one time only and maybe you also want to offer several codes for download.

Plan a user experience to link a new device to the server using one of those codes. Also better plan a “refresh” button to invalidate the old codes and create new ones in case the printed codes get stolen.

Censorship

The original internet was planned with lots of resilience. Even if parts of the internet have issues, the rest will route around it.

Centralisation has added dependencies on a few companies. This results in accidental outages or planned censorship.

Both are totally contrary to the spirit of the internet. By engineering resilience into the software you can protect from outages.

If you are not building a system but administrating one, there are several tools that add redundancy to your current tool set. Especially by disconnecting from centralized services.

The tricky thing: You have to install those programs before the internet fails. And regularly use them to be sure they are operational in case of an emergency.

The programs you currently use will not have to be replaced. Just have those additional programs installed as well.

Mapping censorship

There are several projects mapping internet failures. This can be censorship (Turkey) or power outages causing internet downtime (Venezuela).

OONI by the Tor project

Oooni has globally distributed sensors measuring the reach ability of services. Data can be accessed on a map, by a list of “best of censorship” events and by an API.

The project is Open Source and there is a description how to set up a sensor on a Raspberry Pi.

The whole project is part of the Tor project.

Netblocks

Netblocks is run by a civil society group. Focus is more on written reports based on special internet outage events.

Blocked.org.uk

Censored pages in UK. UK has a voluntary filter for <18 content. This is over-blocking.

This site tests and monitors specific sites.

Censorship countermeasures

Basic countermeasures are based on “have a plan B”. Redundancy.

Messenger

Jabber + OMEMO

Jabber is a chat software. Jabber (aka XMPP) is like E-Mail: You can have an address at any Jabber server, use any kind of Jabber client to access it and contact everyone with a Jabber account.

OMEMO is the encryption technology for Jabber. Just activate it in your client and done.

There a different Jabber clients for example:

  • Conversations for Android
  • Gajim for Linux and Windows

Jabber is de-centralized and this makes it very resilient.

There is also no central directory of user names. Pro: No one is tracking you or your network. Con: You have to give your friends your Jabber address.

Signal

Signal is a free client for mobile phones with a very good encryption. The Con: There is a central directory. Pro: As soon as you register on Signal, all your address book contacts that also use Signal will be in your Signal-connections-list.

Similar to WhatsApp. But without Facebook.

Threema

Threema is a mobile phone communication app. It is cheap but not free. Also: It is closed source - but is getting security reviews. The encryption and the feature set are good and it is a very good messenger and simple to use. I especially like the (optional) key verification that forces people to meet in person and confirm their identity by scanning a QR code. Intuitive and secure.

Telegram

I am not using Telegram. It has several security issues. But on the other hand: Many people are already using it and it “survived” several censorship attempts already.

Use it but be aware: It is less secure to spying attempts than the other messengers listed here. But the widespread adoption has its own benefits.

Browser replacement

Tor browser

The Tor browser is hiding your tracks on the internet. Just install it. It will look like a Firefox browser with a few extra options. You can ignore them - the defaults are OK.

The Tor trick: Your data is sent encrypted over three “Tor nodes” to hide you from the internet.

Some very restrictive states limit the Tor browser. For those there are extra modes to exit their internet.

The Tor browser can access special “.onion” URLs. That is the Dark part of the web.

This may sound spooky. But even Facebook has a an entry door on the Dark side of the web. Facebook on Tor It is is not as big a thing as you may think.

Install the Tor browser and give it a try. You may not need it now. But maybe later.

Network infrastructure

In some regions the web coverage is under-developed. For some political reasons that is quite common in Germany. The Freifunk project is offering free WiFi under the SSID “Freifunk”. Just connect and use the internet.

This project is a good alternative to company owned infrastructure and adds resilience.

If you are responsible for an area where people gather (restaurant, library, …) think about contacting this project and running an own Freifunk router. Which is basically an AP with special configuration.

DNS

Domain Name System is the phone book of the internet. It converts URLs into server IP numbers (IPv4 or IPv6). Ripping entries out of the DNS pre-configured by your ISP is a simple way to censor specific services.

If it looks like that happened to you:

DNS settings are in your Operating System. Some big companies run their own DNS. Try changing the old DNS entries for one of those:

  • Google: 8.8.8.8
  • Cloudflare: 1.1.1.1
  • Quad9: 9.9.9.9

(Yes, all of them were able to get iconic IPv4 addresses).

Blocking on DNS level happened at the “Censorship in Turkey” event.

File sharing

Using OnionShare it is possible to share files. Just drag some files into the box, click the “start sharing” button and send the generated URL to your communication partner. As long as the server is running the partner can download it by simply using the Tor browser.

Further reading

A large collection of alternative to centralised and surveilled services can be found on prism-break.org

Crypto algorithms

Crypto Algorithms are the basic building blocks of encryption. Above them are protocols (“how do we glue algorithms together to achieve our goal ?”). And above the protocols are libraries offering an easy programming interface to use a protocol.

In many cases the user of the library still has to pick the algorithm to slot into the protocol. A basic knowledge of the algorithms will prevent many bugs.

I will skip the mathematics and try to build simple “Good vs Bad” tables. If you want to dig deeper, please read the books in the links.

A good crypto algorithm is created and tested in challenges. It will get a good peer review by other crypto experts. When mathematics improves (and computers get faster as well) the estimated time to crack it will shrink. Moore’s law predicts a increase of processing power by factor 2 every 18 months. GPUs, ASICs and Clouds (lots of cheap computers from Amazon Cloud, for example) can also bring down the attack time.

Normally experts will warn months or even years before a realistic attack on an algorithm is possible. That’s the time to move on to use a better algorithm.

Be prepared to swap the algorithm used in your products and services

If you rely on a crypto book on your desk, check out the date it was published. During the last years new attacks have been invented and some algorithms and protocols did not age well. If your decisions still are based on a book from 1995 they will be wrong - even if the book was great at that time.

Be aware: This chapter is an extreme simplification. If crypto security is an essential part of your project dig deeper and use the further reading section.

Hash functions

Hash functions are one way functions that generate a value of a fixed size from any length of input. One input always generates the same Hash. On the other hand: One Hash can be the same for different inputs.

For security reasons it must be impossible:

  • To revert the process and calculate the input from the Hash
  • To generate two inputs with the same Hash
Name Output Length (Byte) Quality
CRC * Broken
MD5 16 Broken
SHA-1 20 Broken
SHA256 32 Good
SHA512 64 Good
SHA-3 variable Good
BLAKE2 variable Good

A CRC is not a Crypto Hash function. It is good for validating bit flips in data. But not to prevent or detect human attacks. Still some people use it that way…

shattered.io on breaking SHA-1

SHA256 and SHA512 are SHA-2 hashes. Where the number indicates the bit length.

SHA-3 aka Keccak: Is developed as fallback for SHA-2. SHA-2 is still good. But if something should happen to it, there is SHA-3 with is based on a totally different internal principle.

BLAKE2 was in the SHA-3 contest. Its main feature is speed. There are different variants optimized for different architectures. The core ones are:

  • BLAKE2b: for 64 bit platforms
  • BLAKE2s: For 8 to 32 bit platforms

If you need speed, give it a chance.

HMAC or MAC

MAC allows Integrity and Authentication. Simplified: It is a Hash with a shared key involved. That way the parties can authenticate the origin.

Name Quality
Poly1305 Good
SipHash Good

Password hash functions

While other hash functions are efficient, for password hashes we want inefficient hash functions. On a normal server it does not matter that much if 1 or 500 milliseconds are wasted on calculating the Hash. But the attacker wanting to break a database dump with hundreds of thousands Hashes gets into lots of trouble thanks to the in-efficient hash.

Name Comments
Argon2d GPU attack resistance
Argon2i side channel attack resistance
bcrypt Vulnerable to FPGA, ASIC attacks
scrypt Vulnerable to GPU attacks
PBKDF2 Vulnerable to FPGA, ASIC and GPU attacks

Links:

Stream Ciphers

Stream ciphers are used especially in telecommunication to encrypt a data stream (mobile phone voice channel).

Name Quality
A5/1 Broken
A5/2 Broken
RC4 Broken
Salsa20 Good

Block Ciphers

Block Ciphers are the work horse to encrypt large data. Besides selecting the Algorithm and the key length it is also important to use it in the proper mode. There will be an own table for that.

Algorithms

Name Quality
DES Broken
3DES Mediocre
AES Good

3DES is rated mediocre because AES offers a better key-length to protection ratio. You should be using that.

Modes

Block ciphers are encrypting the data block-by-block. The mode defines if and how the encryption of one block influences the encryption of the other blocks.

Name Quality
Electronic Codebook (ECB) Broken
Cipher Block Chaining (CBC) OK
Counter Mode (CTR) Good
Authenticated Enc. .. (AEAD) Perfect

If possible use AEAD.

Some of those modes need more data in addition to the password to initialize the encryption: a number named IV (initialisation vector) or nonce (number used only once). This number can be public. But it has an important requirement: Do not recycle it ! This number must be used once only. For the next data you encrypt use a different one. With that requirement: A counter would do the job pretty well.

Authenticated Encryption

Combining a MAC and an encryption results in Authenticated Encryption.

The most common AE technology is AES Galois Counter Mode (AES-GCM)

One important differentiation is if to do MAC first or encryption. It seems during the years - as experience grew - the shift was towards “Encrypt-then-MAC” as best practice.

Name Quality
Encrypt-and-MAC Bad
MAC-then-encrypt Better
Encrypt-then-MAC Best

MAC and cipher must use distinct keys. But there are foot guns and alternatives to this whole AE complex.

If you go down that road, please check out “further reading” and at least 2 more books. Implementing this is lots of work (months-for experts). Invest your time into smartening up first.

Or use libraries implementing this technology ready-to-use (which I would do).

Asymmetric Ciphers

RSA: you should use 2048-4096 bit key length (security levels of 90 to 128 bits)

Encryption: Cipher text should be padded. RSA-OAEP does this (Optimal Asymmetric Encryption Padding)

For signatures with RSA use RSA-PSS(Probabilistic Signature Scheme)

Key exchange

To do a key agreement/key exchange the state of the art is DH: Diffie-Hellman protocol. It can be used in different flavours.

Name Quality
Anonymous Diffie–Hellman Broken
Authenticated Diffie–Hellman Weak
Menezes–Qu–Vanstone (MQV) Best but complex
  • Anonymous DH is breakable by man-in-the-middle attacks
  • Authenticated Diffie–Hellman: breakable by replay attacks
  • MQV is best but complex

Most often used is Authenticated DH

Elliptic Curve Cryptography (ECC)

Elliptic curve based cryptography is an upgrade on many crypto protocols. It offers more security for less key length. And thanks to the smaller keys it is often faster.

If possible replace your RSA and DH with ECC.

EC crypto depends on one special parameter: the curve it runs on. The curve has to be special. You can not make up your own. Instead use one of the standard curves:

  • NIST curves
  • Curve25519 (which is very common)

Key length

Depending on your computing power, lifetime of your product and adversary this may vary. But sane best-practice key lengths are:

  • Asymmetric: >= 3248 bit
  • Elliptic Curve to replace classical asymmetric crypto: >= 256 bit
  • Symmetric: >= 128 bit

A source for a more specific evaluation of your required key length is here.

Best practice

Further reading

Serious Cryptography by Jean-Philippe Aumasson

Serious Cryptography is Mathematics paired with some hands-on. It contains lots of common mistakes being made when using those algorithms and protocols. It should be on your desk when building something with cryptography.

The Mozilla TLS guide

Mozilla TLS guide is a collection of TLS server settings for different situations. A good cheat sheet ranking the current quality of algorithms in a pragmatic (“don’t break the web”) environment.

BetterCrypto.org

BetterCrypto is a project aimed at helping admins. They offer a free manual with lots of specific crypto settings for different applications. It also contains basic algorithm overviews.