Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Fundamentals › Security

Encryption

What is encryption, and what happens without the key?

Why it exists — Information that must be read back in its original form later, such as a phone number or a card number, cannot be recovered if you turn it into a hash, and if you leave it as plain text, anyone who peeks at the communication or steals the storage can read all of it. Encryption lets only the party who knows the key turn it back into the original value, so the party that needs the value can use it again, and for a person without the key it stays a value that cannot be recognized.

Where it's used today — It is used to hide the text that HTTPS exchanges, and also when you store in a database personal information that must be read again, such as an address, a phone number, and an account number. In Java, you make a key with KeyGenerator of the standard library javax.crypto and encrypt and decrypt with Cipher. Do not write the key in the code; keep it in an environment variable or in a service that holds keys separately. A password that does not need to be read again is not encrypted but stored as a hash.

Encryption means calculating text together with a key to turn it into bytes that cannot be recognized. In Java, the standard library (the javax.crypto package) does this work. KeyGenerator makes a key, and Cipher calculates with that key. The sender sets the Cipher to encryption mode (Cipher.ENCRYPT_MODE) and calls doFinal, and the receiver, who has the same key, sets the Cipher to decryption mode (Cipher.DECRYPT_MODE) and calls doFinal to get the original text back. If the key is different, you cannot get it back, so what you must protect is not the value but the key. In this lab you turn encryption on or off, change one byte on the way, and switch the receiver's key between the same one and a different one, and you actually run it to see what is visible in the middle and what the receiver read.

Checked against real execution · Eight combinations of the code on the screen (KeyGenerator, Cipher AES/GCM/NoPadding, GCMParameterSpec, doFinal) were compiled with javax.tools and run on JDK 21 exactly as they are, and the output and the exception (AEADBadTagException, Tag mismatch) were checked against the model. The code was also run again with real random values, and the calculation was checked with Node.js and the NIST test vectors

Concepts in this lab

Encryption
Encryption is calculating text (plaintext) together with a key to turn it into a value that cannot be recognized (ciphertext). A party that has the same key decrypts that value and gets the original text back, but a party that has no key cannot. Text that is sent or stored without encryption can be read as it is by anyone in the middle. The difference from hashing is that hashing makes it so that no one can turn the value back into the original text, while encryption makes it so that only a party that has the key can turn it back. AES is a symmetric block cipher defined by FIPS 197 that does both encryption and decryption, and in Java you use it through the javax.crypto.Cipher class.
Decryption
Where it's used today — Decrypt only at the moment when the original value is really needed, as when sending a text message to a phone number that was stored encrypted. When showing it on a screen, even after decrypting, part of it is sometimes hidden, as in 010-****-1234.
Decryption is calculating an encrypted value together with a key to turn it back into the original text. In the symmetric-key method, you must put in the same key that was used to encrypt. A method such as AES-GCM, which attaches a check value (tag) to the value, reports a failure instead of giving out text when the key is different or the value was changed and the tag does not match (FAIL in SP 800-38D), and Java's Cipher throws AEADBadTagException in that case. In a method with no check value, a different key can give wrong bytes with no exception, so you must not trust that the key was right just because the decryption finished.
Key
Why it exists — If the calculation method itself is kept secret, then once the method leaks, every place that uses it has to be changed. With a separate key, the calculation method can be made public so that many people can verify it, and when a key leaks, only the key has to be replaced.
Where it's used today — In Java, an AES key is made with KeyGenerator, and a key that has been used for a long time is sometimes replaced with a new one at set intervals. To decrypt values that were encrypted with an old key even after switching to a new key, the old key is kept as well.
A key is a value that you put into the encryption and decryption calculation together with the text or the value. AES uses keys that are 128, 192, or 256 bits long. The algorithm is a public standard such as FIPS 197, and whether you can decrypt a value depends on whether you have the key, so what you must protect is the key. In the symmetric-key method, the sender and the receiver have the same key, and sharing that key safely is a separate task. In GCM, you must use a different IV (nonce) each time you encrypt with the same key, and if it is repeated, it becomes open to forgery attacks (SP 800-38D section 8, the Cipher documentation).
KeyGenerator and SecretKey
Where it's used today — You call KeyGenerator when you make a new key for the first time or in test code. In a service, the key you made is kept in an environment variable or in a service that holds keys (such as KMS), and at startup it is read and turned into a key with SecretKeySpec.
KeyGenerator is a class, provided by the Java standard library (the javax.crypto package), that makes a key for the method that encrypts and decrypts with the same key (the symmetric-key method). You do not create it with new; you get it by the name of the method, as in KeyGenerator.getInstance("AES"), set the key length in bits with init(256), and then when you call generateKey(), a random key comes back as the type SecretKey. SecretKey is a Java interface that stands for a symmetric-key key that must not be shown to others, and you get the bytes of the key with getEncoded(). To turn saved key bytes back into a SecretKey, use new SecretKeySpec(bytes, "AES").
Cipher
Where it's used today — Cipher is called in code that encrypts personal information before storing it in a database, and in code that encrypts when a column value is saved and decrypts when it is read with a JPA AttributeConverter. Libraries that wrap Cipher, such as Encryptors.stronger of Spring Security, are also used, and inside them too the calculation is done by Cipher.
Cipher is a class, provided by the Java standard library (the javax.crypto package), that encrypts and decrypts. You do not create it with new; you get it with text that gives "method/mode/padding", as in Cipher.getInstance("AES/GCM/NoPadding"). You decide what it will do by passing Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE, a key, and the values the mode needs (GCMParameterSpec for GCM) to init, and when you pass bytes to doFinal, the calculated bytes come back. The same class either encrypts or decrypts depending on the mode chosen in init. If the tag does not match while decrypting with AES-GCM, doFinal throws javax.crypto.AEADBadTagException.
IV (initialization vector)
An IV (initialization vector) is a value that you put in together with the key when you encrypt, and that you choose anew each time you encrypt. In GCM it is also called a nonce, and a length of 12 bytes (96 bits) is recommended (SP 800-38D section 5.2.1.1). Even if you encrypt the same text with the same key, the resulting bytes differ if the IV differs. You must not use the same IV again with the same key (SP 800-38D section 8). An IV is not a key, and the receiver also needs the same IV to decrypt, so it is sent together with the ciphertext. In Java, you pass a byte array filled by SecureRandom to init of Cipher as new GCMParameterSpec(128, iv).
AES-GCM and authentication tag
Why it exists — With a method that only hides the text, a person without the key could change the bytes of the ciphertext and so change the text that the receiver decrypts. So a method that does the hiding and the checking for changes in one go came into use.
Where it's used today — It is used in the AES-GCM cipher suites of HTTPS (TLS), in encryption of personal information stored in a database, and in Encryptors.stronger of Spring Security.
AES-GCM is the use of AES in GCM mode, and it does two things together: hiding the text and checking that the bytes were not changed (SP 800-38D section 3). When it encrypts, it calculates a check value (an authentication tag) and attaches it after the ciphertext, and when it decrypts, it calculates the tag again from the received bytes and compares it. If the key is different or even one byte was changed, the tag does not match, and Java's Cipher does not return the text but throws javax.crypto.AEADBadTagException. In Java you get it with Cipher.getInstance("AES/GCM/NoPadding"), and the first argument of GCMParameterSpec sets the tag length (128 bits). A method with no tag (AES/CTR and others) decrypts even changed bytes without an exception.
Symmetric-key cryptography and public-key cryptography
Where it's used today — In HTTPS (TLS), public-key cryptography is used when the connection is set up, to verify the signature of the server certificate and to exchange keys, and the HTTP data that follows is encrypted with a symmetric key such as AES. Values stored in a database, such as card numbers, are encrypted with a symmetric key, and the key pair used for SSH login is a public-key one.
Symmetric-key cryptography uses the same key to encrypt and to decrypt. It is fast, but it has the problem that the key must be shared safely with the other party (AES). Public-key cryptography uses a pair of keys, a public key and a private key. Data encrypted with the public key can be decrypted only with the private key, so there is no key-sharing problem, but it is slow (RSA). In practice, public-key cryptography is used to exchange a symmetric key safely, and then the symmetric key encrypts the data.

Try these

Running with the default settings

  1. The line KeyGenerator gen = KeyGenerator.getInstance("AES"); gets a tool that makes AES keys. KeyGenerator is a class that Java provides (in the javax.crypto package), and "AES" passed to getInstance is the name of the calculation method. AES is a method set by a US standard (NIST FIPS 197) that encrypts and decrypts with the same key.
  2. The line gen.init(256); sets the key length to 256 bits (32 bytes), and the line SecretKey key = gen.generateKey(); makes one random key. The type of the variable key, SecretKey, is a type that Java provides, and it stands for a key that must not be shown to others.
  3. The line byte[] iv = new byte[12]; makes an array of 12 bytes, and the line new SecureRandom().nextBytes(iv); fills that array with random bytes. SecureRandom is a class that Java provides that makes random values good enough for cryptography. The iv is not a key; it is a value that you choose anew each time you encrypt with the same key. You must not use the same iv again with the same key.
  4. The line Cipher encCipher = Cipher.getInstance("AES/GCM/NoPadding"); gets the Cipher that will do the calculation. Cipher is a standard Java class that encrypts and decrypts, and "AES/GCM/NoPadding" means to use AES in GCM mode, without padding (extra bytes added at the end). Then the line encCipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv)); sets this Cipher to encryption mode and passes the key key and the iv. The 128 is the length, 128 bits, of the check value (the tag) that is attached at the end.
  5. In the line byte[] sent = encCipher.doFinal("Card number: 1234".getBytes(StandardCharsets.UTF_8)); getBytes turns the text into 17 UTF-8 bytes, and doFinal encrypts those bytes with the key and the iv. The sent that comes back is 33 bytes. The first 17 bytes are the encrypted text, and the last 16 bytes are the check value (the tag).
  6. The line System.out.println(new String(sent, StandardCharsets.UTF_8)); is the same as someone in the middle (the network or the database) turning these bytes into text to look at them. As the first line, garbled text mixed with � and meaningless symbols is printed, and neither "Card number" nor "1234" is visible. The key and the iv are chosen at random on each run, so the shape of the garbled text is different every time.
  7. The line Cipher decCipher = Cipher.getInstance("AES/GCM/NoPadding"); gets a Cipher of the same kind on the receiving side too, and the line decCipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv)); sets decryption mode, the same key key, and the same iv. The receiver also needs the iv to decrypt, so in practice you send the iv together with the ciphertext. This code is in a single main, so it uses the variable iv as it is.
  8. In the line byte[] read = decCipher.doFinal(sent); doFinal calculates the tag again from the received bytes and checks that it matches the tag at the end, and because it matches, it returns the original 17 bytes. new String(read, StandardCharsets.UTF_8) on the last line turns those bytes into text and prints Card number: 1234 as the second line. This is because the same key and the same iv as at encryption were put in.

Result of this run

Code

// Only the lines inside main are shown (the class and main declarations and the imports are omitted)

// ① Make a key: KeyGenerator is a class that Java provides
KeyGenerator gen = KeyGenerator.getInstance("AES");   // Get a tool that makes AES keys
gen.init(256);                                        // Set the key length to 256 bits
SecretKey key = gen.generateKey();                    // Make one random key

// ② Sender: encrypt with Cipher (a class that Java provides)
byte[] iv = new byte[12];                             // Make an array of 12 bytes
new SecureRandom().nextBytes(iv);                     // Fill iv with random bytes
Cipher encCipher = Cipher.getInstance("AES/GCM/NoPadding");             // Get a Cipher that calculates with AES-GCM
encCipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv)); // Set encryption mode, the key, and iv
byte[] sent = encCipher.doFinal("Card number: 1234".getBytes(StandardCharsets.UTF_8)); // Encrypt the bytes of the text

// ③ In the middle (network or database): turn the passing bytes into text and look
System.out.println(new String(sent, StandardCharsets.UTF_8));

// ④ Receiver: decrypt with the same key
Cipher decCipher = Cipher.getInstance("AES/GCM/NoPadding");             // Get a Cipher of the same kind
decCipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv)); // Set decryption mode, the same key, and the same iv
byte[] read = decCipher.doFinal(sent);                // Decrypt and get the original bytes
System.out.println(new String(read, StandardCharsets.UTF_8)); // Turn the bytes into text and print it

Assumptions of this model

It was checked against real execution on Java JDK 21.0.12.1 (verify/plain/CryptoBasicProbe.java, comparison tool cmp_crypto_basic.js). For each of the eight combinations, the code on the screen (the lines inside main, without the one header comment line) was put inside main without changing a single character, only the imports and the class and main declarations (throws Exception) were added, and it was compiled with javax.tools and run, and the standard output and the thrown exception were captured. What was checked is what is visible in the middle (the first line), what the receiver read (the second line), the name and message of the thrown exception (javax.crypto.AEADBadTagException, Tag mismatch), and that the second line is not printed when the exception occurs. The key and the iv are chosen at random on each run, so only during the comparison a test security provider was put at the front of the order so that SecureRandom gives fixed bytes (00, 01, 02, …). The code on the screen is unchanged, and it was checked separately that KeyGenerator.init(256) and new SecureRandom() use those bytes. When the same code was run again with real random values, the kinds of results (the text that was read, the name of the exception, the number of output lines) were the same. The shape of the garbled text changes with the key and the iv, so only the number of bytes is written on the screen. The facts that the step sentences rely on were also checked by running. "Card number: 1234" is 17 bytes in UTF-8, and the result of doFinal was 33 bytes (17 bytes of encrypted text and a 16-byte tag). The text made by turning those bytes into text with new String(…, StandardCharsets.UTF_8) had � mixed in, and had neither "Card" nor "1234". With two random keys, decrypting with a different key threw AEADBadTagException all 100 times out of 100, and flipping one bit at any position of the 33 bytes threw the same exception all 33 times out of 33. When the same text was encrypted twice with the same key and only a newly chosen iv, the two results differed and both could be decrypted. When an attempt was made to set the Cipher that was used for encryption to encryption mode again with the same key and the same iv, Java blocked it with InvalidAlgorithmParameterException (Cannot reuse iv for GCM encryption). That sent[16] is the position that encrypted the character "4" was confirmed by separately running the counter method with which GCM calculates the text part (SP 800-38D section 7.1) as AES/CTR and decrypting the changed byte without a tag check, which gave Card number: 1235. When a byte at the same position of the bytes encrypted with AES/CTR/NoPadding, which has no tag, was changed, Card number: 1235 came out without an exception, and when it was decrypted with a different key, 17 bytes that were not the original text came out without an exception. In the bytes that were not encrypted, sent[16] is "4" (0x34), and flipping one bit gives "5" (0x35). Whether the calculation follows the standard was checked in two ways. The bytes (ciphertext and tag) made by encrypting the same key, iv, and text with aes-256-gcm of Node.js were the same, byte for byte, as the result of doFinal of Java, and Node.js decrypted the value from Java only with the same key and could not decrypt it with a different key or changed bytes. Also, from the GCM test vectors published by the NIST Cryptographic Algorithm Validation Program (CAVP) (gcmEncryptExtIV256.rsp and gcmDecrypt256.rsp in gcmtestvectors.zip; key 256 bits, IV 96 bits, text 128 bits, no additional data, tag 128 bits), the ciphertext and tag of one encryption and the results of two decryptions (one that passed and one FAIL) were the same as the Java calculation. The names of KeyGenerator, SecretKey, SecureRandom, Cipher, and GCMParameterSpec and how to call them were checked by the compilation and running above, and that the first argument 128 of GCMParameterSpec is the tag length (in bits) was checked by the result becoming 16 bytes longer. The documentation is what was opened and checked directly in the previous edition. Item 3 of the preface of NIST FIPS 197 (2023 update) introduces AES as a symmetric block cipher that can encrypt and decrypt, and says the key length is 128, 192, or 256 bits. NIST SP 800-38D (2007 edition) says in section 3 that GCM guarantees both confidentiality and authentication of data, defines in sections 5.2.2 and 7.2 that authenticated decryption gives the text if the tag matches and FAIL instead of the text if it does not, requires in section 8 that the same IV is not repeated with the same key, and recommends in section 5.2.1.1 an IV length of 96 bits. The Java 21 Cipher documentation explains that in AEAD modes (GCM and others) the tag is appended after the ciphertext and verified when decrypting, and tells you to change the IV every time you encrypt with the same key, and the AEADBadTagException documentation explains that it is thrown when a Cipher of an AEAD mode cannot verify the tag. This lab covers only the method in which the sender and the receiver use the same key (symmetric-key encryption). The code on the screen writes the sender and the receiver in one main, so it shares the variables key and iv as they are. How to actually send the iv together with the ciphertext (for example, by putting it in front), how the receiver safely gets the same key (key delivery), and how to store keys safely are not covered. The method with two keys (public key) and signatures are covered in the "In-depth lab: Hashing, encryption, and signatures".

Previous lab: Hashing · Next lab: Origins

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these