This site is the archived OWASP Foundation Wiki and is no longer accepting Account Requests.
To view the new OWASP Foundation website, please visit https://owasp.org
Difference between revisions of "Using the Java Cryptographic Extensions"
(moved Spanish content to its own page) |
m (→AES Encryption and Decryption) |
||
(10 intermediate revisions by 5 users not shown) | |||
Line 1: | Line 1: | ||
− | |||
− | |||
== Overview == | == Overview == | ||
Line 100: | Line 98: | ||
package org.owasp.java.crypto; | package org.owasp.java.crypto; | ||
− | import javax.crypto. | + | import javax.crypto.*; |
− | import javax.crypto. | + | import javax.crypto.spec.IvParameterSpec; |
− | import | + | import java.io.UnsupportedEncodingException; |
− | + | import java.nio.ByteBuffer; | |
+ | import java.security.InvalidAlgorithmParameterException; | ||
+ | import java.security.InvalidKeyException; | ||
import java.security.NoSuchAlgorithmException; | import java.security.NoSuchAlgorithmException; | ||
− | import java.security. | + | import java.security.SecureRandom; |
− | import java. | + | import java.util.Base64; |
− | |||
− | |||
− | |||
− | |||
− | |||
+ | // @formatter:off | ||
/** | /** | ||
− | * @author Joe Prasanna Kumar | + | * @author Chuck Eastus |
− | * This | + | * Reworked from Joe Prasanna Kumar's sample with suggestions and notes made by Kevin W. Wall. |
− | * 1. | + | * This class demonstrates encrypting and decrypting a string message using the AES algorithm. |
− | * 2. | + | * Steps: |
− | * | + | * 1. Generate an AES key of the desired length (in bits) using an AES KeyGenerator. |
− | * | + | * 2. Get a Cipher instance of the desired algorithm, mode, and padding. |
− | * | + | * 3. Generate an initialization vector for our message of the same size as the Cipher's blocksize. |
− | * | + | * 4. Initialize the Cipher instance for encryption using the key and initialization vector. |
− | * | + | * 5. Use the Cipher to encrypt the message (after encoding it to a byte[] using the named Charset), and then append |
− | * | + | * the encrypted data to the IV and Base64-encode the result. |
− | * | + | * 6. Get a new Cipher instance of the same algorithm, mode, and padding used for encryption. |
− | * | + | * 7. Base64-decode and split the data into the IV and the encrypted data, and then initialize the cipher for |
+ | * decryption with the same key used for encryption (symmetric), the IV, and the encrypted data. | ||
+ | * 8. Use the Cipher to decrypt the data, convert it to a String using the named Charset, and display the message. | ||
+ | * | ||
+ | * Notes on padding: | ||
+ | * PKCS7 padding is actually technically the correct padding name, but Java blew it and called it PKCS5PADDING. | ||
+ | * Technically, PKCS5 padding only applies to ciphers with a cipher block size of 64-bits, not 128-bits, but both PKCS5 | ||
+ | * and PKCS7 padding act identically for block sizes <= 255 bits. | ||
+ | * Be sure to specify the mode explicitly as most JCE providers default to ECB mode, which is not secure! | ||
+ | * For this example, we are use CFB mode with no padding in order to avoid padding attacks. | ||
+ | * | ||
+ | * Notes on initialization vectors (IVs): | ||
+ | * The IV must be saved for later decryption and should not be reused for other encryption operations. It can be stored | ||
+ | * separately or sent along with the encrypted data. Usually, the encrypted data is appended to the IV and the result | ||
+ | * is encoded then stored or transmitted. | ||
*/ | */ | ||
+ | // @formatter:on | ||
public class AES { | public class AES { | ||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | + | public static final int keyLength = 128; | |
− | + | public static final String charEnc = "UTF-8"; | |
− | = | + | public static final String transformationString = "AES/CFB/NoPadding"; |
− | + | ||
− | + | public static void main(String[] args) { | |
+ | |||
+ | String message = "Hello World of Encryption using AES"; | ||
+ | String cipherText; | ||
+ | |||
+ | try { | ||
+ | // Step 1 | ||
+ | KeyGenerator keyGen = KeyGenerator.getInstance("AES"); | ||
+ | keyGen.init(keyLength); | ||
+ | SecretKey secretKey = keyGen.generateKey(); | ||
+ | |||
+ | // Step 2 | ||
+ | Cipher aesCipherForEncryption = Cipher.getInstance(transformationString); | ||
+ | |||
+ | // Step 3 | ||
+ | byte[] iv = new byte[aesCipherForEncryption.getBlockSize()]; | ||
+ | SecureRandom prng = new SecureRandom(); | ||
+ | prng.nextBytes(iv); | ||
− | + | // Step 4 | |
− | + | aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv)); | |
− | |||
− | + | // Step 5 | |
− | + | byte[] encrypted = aesCipherForEncryption.doFinal(message.getBytes(charEnc)); | |
− | + | ByteBuffer cipherData = ByteBuffer.allocate(iv.length + encrypted.length); | |
− | + | cipherData.put(iv); | |
− | + | cipherData.put(encrypted); | |
− | + | cipherText = new String(Base64.getEncoder().encode(cipherData.array()), charEnc); | |
+ | System.out | ||
+ | .println("Encrypted and encoded message is: " + new String(Base64.getEncoder().encode(encrypted), charEnc)); | ||
+ | System.out.println(cipherText); | ||
+ | System.out.println("\nThe receiver will now initialize the cipher using the IV and decrypt the ciphertext"); | ||
− | + | // Step 6 | |
+ | Cipher aesCipherForDecryption = Cipher.getInstance(transformationString); | ||
− | / | + | // Step 7 |
− | + | cipherData = ByteBuffer.wrap(Base64.getDecoder().decode(cipherText.getBytes(charEnc))); | |
− | + | iv = new byte[aesCipherForDecryption.getBlockSize()]; | |
− | + | cipherData.get(iv); | |
− | + | encrypted = new byte[cipherData.remaining()]; | |
− | + | cipherData.get(encrypted); | |
− | + | aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | + | // Step 8 | |
− | + | byte[] decrypted = aesCipherForDecryption.doFinal(encrypted); | |
− | + | System.out.println("Decrypted text message is: " + new String(decrypted, charEnc)); | |
− | + | } catch(NoSuchAlgorithmException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | UnsupportedEncodingException ex) { | |
− | + | System.err.println(ex); | |
− | + | } | |
− | + | } | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
} | } | ||
</pre> | </pre> | ||
− | [[Category: | + | |
+ | [[Category:Java]] |
Latest revision as of 16:38, 10 July 2019
Overview
Java Cryptographic Extensions (JCE) is a set of Java API's which provides cryptographic services such as encryption, secret Key Generation, Message Authentication code and Key Agreement. The ciphers supported by JCE include symmetric, asymmetric, block and stream ciphers. JCE was an optional package to JDK v 1.2.x and 1.3.x. JCE has been integrated into JDK v1.4.
JCE API's are implemented by Cryptographic Service Providers. Each of these cryptographic service providers implements the Service Provider Interface which specifies the functionalities which needs to be implemented by the service providers. Programmers can plugin any Service Providers for performing cryptographic functionalities provided by JCE. J2SE comes with a default provider named SunJCE.
Symmetric Encryption Algorithms provided by SunJCE
- DES - default keylength of 56 bits
- AES -
- RC2, RC4 and RC5
- IDEA
- Triple DES – default keylength 112 bits
- Blowfish – default keylength 56 bits
- PBEWithMD5AndDES
- PBEWithHmacSHA1AndDESede
- DES ede
Modes of Encryption
- ECB
- CBC
- CFB
- OFB
- PCBC
Asymmetric Encryption Algorithms implemented by SunJCE
- RSA
- Diffie-Hellman – default keylength 1024 bits
Hashing / Message Digest Algorithms implemented by SunJCE
- MD5 – default size 64 bytes
- SHA1 - default size 64 bytes
Examples
SecureRandom
SecureRandom class is used to generate a cryptographically strong pseudo random number by using a PRNG Algorithm. The following are the advantages of using SecureRandom over Random. 1. SecureRandom produces a cryptographically strong pseudo random number generator. 2. SecureRandom produces cryptographically strong sequences as described in RFC 1750: Randomness Recommendations for Security
package org.owasp.java.crypto; import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Encoder; /** * @author Joe Prasanna Kumar * This program provides the functionality for Generating a Secure Random Number. * * There are 2 ways to generate a Random number through SecureRandom. * 1. By calling nextBytes method to generate Random Bytes * 2. Using setSeed(byte[]) to reseed a Random object * */ public class SecureRandomGen { /** * @param args */ public static void main(String[] args) { try { // Initialize a secure random number generator SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); // Method 1 - Calling nextBytes method to generate Random Bytes byte[] bytes = new byte[512]; secureRandom.nextBytes(bytes); // Printing the SecureRandom number by calling secureRandom.nextDouble() System.out.println(" Secure Random # generated by calling nextBytes() is " + secureRandom.nextDouble()); // Method 2 - Using setSeed(byte[]) to reseed a Random object int seedByteCount = 10; byte[] seed = secureRandom.generateSeed(seedByteCount); // TBR System.out.println(" Seed value is " + new BASE64Encoder().encode(seed)); secureRandom.setSeed(seed); System.out.println(" Secure Random # generated using setSeed(byte[]) is " + secureRandom.nextDouble()); } catch (NoSuchAlgorithmException noSuchAlgo) { System.out.println(" No Such Algorithm exists " + noSuchAlgo); } } }
AES Encryption and Decryption
package org.owasp.java.crypto; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Base64; // @formatter:off /** * @author Chuck Eastus * Reworked from Joe Prasanna Kumar's sample with suggestions and notes made by Kevin W. Wall. * This class demonstrates encrypting and decrypting a string message using the AES algorithm. * Steps: * 1. Generate an AES key of the desired length (in bits) using an AES KeyGenerator. * 2. Get a Cipher instance of the desired algorithm, mode, and padding. * 3. Generate an initialization vector for our message of the same size as the Cipher's blocksize. * 4. Initialize the Cipher instance for encryption using the key and initialization vector. * 5. Use the Cipher to encrypt the message (after encoding it to a byte[] using the named Charset), and then append * the encrypted data to the IV and Base64-encode the result. * 6. Get a new Cipher instance of the same algorithm, mode, and padding used for encryption. * 7. Base64-decode and split the data into the IV and the encrypted data, and then initialize the cipher for * decryption with the same key used for encryption (symmetric), the IV, and the encrypted data. * 8. Use the Cipher to decrypt the data, convert it to a String using the named Charset, and display the message. * * Notes on padding: * PKCS7 padding is actually technically the correct padding name, but Java blew it and called it PKCS5PADDING. * Technically, PKCS5 padding only applies to ciphers with a cipher block size of 64-bits, not 128-bits, but both PKCS5 * and PKCS7 padding act identically for block sizes <= 255 bits. * Be sure to specify the mode explicitly as most JCE providers default to ECB mode, which is not secure! * For this example, we are use CFB mode with no padding in order to avoid padding attacks. * * Notes on initialization vectors (IVs): * The IV must be saved for later decryption and should not be reused for other encryption operations. It can be stored * separately or sent along with the encrypted data. Usually, the encrypted data is appended to the IV and the result * is encoded then stored or transmitted. */ // @formatter:on public class AES { public static final int keyLength = 128; public static final String charEnc = "UTF-8"; public static final String transformationString = "AES/CFB/NoPadding"; public static void main(String[] args) { String message = "Hello World of Encryption using AES"; String cipherText; try { // Step 1 KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(keyLength); SecretKey secretKey = keyGen.generateKey(); // Step 2 Cipher aesCipherForEncryption = Cipher.getInstance(transformationString); // Step 3 byte[] iv = new byte[aesCipherForEncryption.getBlockSize()]; SecureRandom prng = new SecureRandom(); prng.nextBytes(iv); // Step 4 aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv)); // Step 5 byte[] encrypted = aesCipherForEncryption.doFinal(message.getBytes(charEnc)); ByteBuffer cipherData = ByteBuffer.allocate(iv.length + encrypted.length); cipherData.put(iv); cipherData.put(encrypted); cipherText = new String(Base64.getEncoder().encode(cipherData.array()), charEnc); System.out .println("Encrypted and encoded message is: " + new String(Base64.getEncoder().encode(encrypted), charEnc)); System.out.println(cipherText); System.out.println("\nThe receiver will now initialize the cipher using the IV and decrypt the ciphertext"); // Step 6 Cipher aesCipherForDecryption = Cipher.getInstance(transformationString); // Step 7 cipherData = ByteBuffer.wrap(Base64.getDecoder().decode(cipherText.getBytes(charEnc))); iv = new byte[aesCipherForDecryption.getBlockSize()]; cipherData.get(iv); encrypted = new byte[cipherData.remaining()]; cipherData.get(encrypted); aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); // Step 8 byte[] decrypted = aesCipherForDecryption.doFinal(encrypted); System.out.println("Decrypted text message is: " + new String(decrypted, charEnc)); } catch(NoSuchAlgorithmException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | UnsupportedEncodingException ex) { System.err.println(ex); } } }