Skip to content

Commit 9c57b64

Browse files
committed
updates examples according to guidlines (refs #7)
1 parent df0b391 commit 9c57b64

14 files changed

+195
-76
lines changed

CHANGELOG.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
77

88
## [Unreleased]
99

10+
### Changed
11+
12+
- Changed class names to conform with guidelines
13+
- Added demonstrate-methods for all examples
14+
- Corrected meta format for file encryption example
15+
16+
### Fixed
17+
18+
- Added missing UTF-8 encoding in assymetric encryption example
19+
- Fixed file encryption not needing trim anymore
20+
- Fixed Headings according to guidlines
21+
- Fixed import statements not expclicit in file encryption example
22+
1023
## [0.3.0] - 2018-07-18
1124

1225
### Changed

java_file_encryption_symmetric_password_based.md

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,42 @@
11
---
2-
title: Password based symmetric file encryption in Java using JDK
2+
title: Java Password based symmetric file encryption using JDK
33
keywords: sample
44
summary: "Password based symmetric file encryption in Java"
55
permalink: java_file_encryption_symmetric_password_based.html
66
folder: Java JDK
7+
references: [
8+
# Place a list of references used to create and/or understand this example.
9+
{
10+
url: "https://docs.oracle.com/javase/10/docs/api/javax/crypto/Cipher.html",
11+
description: "Java JDK Ciper"
12+
}
13+
]
14+
authors: [
15+
{
16+
name: "Kai Mindermann",
17+
url: "https://github.com/kmindi"
18+
}
19+
]
20+
# List all reviewers that reviewed this version of the example. When the example is updated all old reviews
21+
# must be removed from the list below and the code has to be reviewed again. The complete review process
22+
# is documented in the main repository of CryptoExamples
23+
current_reviews: [
24+
25+
]
26+
# Indicates when this example was last updated/created. Reviews don't change this.
27+
last_updated: "2018-08-02"
728
tags: [Java, AES, GCM, PBKDF2, Salt, AEAD]
829
---
930

1031
## Use cases
1132

12-
- password based encryption of a file
13-
- previously shared common secret (password)
33+
- Password based symmetric encryption of a file
34+
35+
## Java version
36+
37+
- JDK 11
1438

15-
## Sample Code for Java based symmetric file encryption using AES-GCM and PBKDF2
39+
## Example Code for Java Password based symmetric file encryption using AES-GCM and PBKDF2
1640

1741
```java
1842
{% include_relative src/main/java/com/cryptoexamples/java/ExampleFileEncryptionInOneMethod.java %}

java_string_encryption_asymmetric.md

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
title: Asymmetric String Encryption using Java JDK
2+
title: Java Asymmetric String Encryption using JDK
33
keywords: sample
44
summary: "Asymmetric String Encryption in Java"
55
permalink: java_asymmetric_string_encryption.html
@@ -24,15 +24,19 @@ current_reviews: [
2424

2525
]
2626
# Indicates when this example was last updated/created. Reviews don't change this.
27-
last_updated: "2018-05-13"
27+
last_updated: "2018-08-02"
2828
tags: [Java, RSA, Asymmetric, String, Encryption]
2929
---
3030

3131
## Use cases
3232

33-
-
33+
- Asymmetric encryption
3434

35-
## Sample Code for Java based asymmetric encryption
35+
## Java version
36+
37+
- JDK 11
38+
39+
## Example Code for Java Asymmetric String Encryption using RSA 4096
3640

3741
```java
3842
{% include_relative src/main/java/com/cryptoexamples/java/ExampleAsymmetricStringEncryptionInOneMethod.java %}

java_string_encryption_key_based_symmetric.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ current_reviews: [
2424

2525
]
2626
# Indicates when this example was last updated/created. Reviews don't change this.
27-
last_updated: "2018-05-13"
27+
last_updated: "2018-08-02"
2828
tags: [Java, AES, GCM, Salt, AEAD]
2929
---
3030

@@ -33,7 +33,11 @@ tags: [Java, AES, GCM, Salt, AEAD]
3333
- Random key generation
3434
- String encryption
3535

36-
## Sample Code for Java based symmetric encryption using AES-GCM and generation of keys
36+
## Java version
37+
38+
- JDK 11
39+
40+
## Example Code for Java String Encryption with key generation using AES-GCM
3741

3842
```java
3943
{% include_relative src/main/java/com/cryptoexamples/java/ExampleStringEncryptionKeyBasedInOneMethod.java %}

java_string_encryption_password_based_symmetric.md

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,20 @@ current_reviews: [
2424

2525
]
2626
# Indicates when this example was last updated/created. Reviews don't change this.
27-
last_updated: "2018-05-13"
27+
last_updated: "2018-08-02"
2828
tags: [Java, AES, GCM, PBKDF2, Salt, AEAD]
2929
---
3030

3131
## Use cases
3232

3333
- Password based encryption
3434
- Previously shared common secret (password)
35-
-
3635

37-
## Sample Code for Java based symmetric encryption using AES-GCM and PBKDF2
36+
## Java version
37+
38+
- JDK 11
39+
40+
## Example Code for Java Password Based String Encryption using AES-GCM and PBKDF2
3841

3942
```java
4043
{% include_relative src/main/java/com/cryptoexamples/java/ExampleStringEncryptionPasswordBasedInOneMethod.java %}

java_string_hash.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,19 @@ current_reviews: [
2424

2525
]
2626
# Indicates when this example was last updated/created. Reviews don't change this.
27-
last_updated: "2018-05-13"
27+
last_updated: "2018-08-02"
2828
tags: [Java, hash, SHA, SHA-512]
2929
---
3030

3131
## Use cases
3232

3333
- Verifying if a string has been changed
3434

35-
## Sample Code for Java based hashing of a String using SHA-512, BASE64 and UTF-8 encoding
35+
## Java version
36+
37+
- JDK 11
38+
39+
## Example Code for Java String Hashing using SHA-512, BASE64 and UTF-8 encoding
3640

3741
```java
3842
{% include_relative src/main/java/com/cryptoexamples/java/ExampleHashInOneMethod.java %}

java_string_sign.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,19 @@ current_reviews: [
2424

2525
]
2626
# Indicates when this example was last updated/created. Reviews don't change this.
27-
last_updated: "2018-05-13"
27+
last_updated: "2018-08-02"
2828
tags: [Java, hash, SHA, SHA-512]
2929
---
3030

3131
## Use cases
3232

3333
- verifying if a string has been changed
3434

35-
## Sample Code for Java based signing of a String using SHA-512, RSA 4096, BASE64 and UTF-8 encoding
35+
## Java version
36+
37+
- JDK 11
38+
39+
## Example Code for Java String Signing using SHA-512, RSA 4096, BASE64 and UTF-8 encoding
3640

3741
```java
3842
{% include_relative src/main/java/com/cryptoexamples/java/ExampleSignatureInOneMethod.java %}
Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import javax.crypto.Cipher;
55
import javax.crypto.IllegalBlockSizeException;
66
import javax.crypto.NoSuchPaddingException;
7+
import java.nio.charset.StandardCharsets;
78
import java.security.InvalidKeyException;
89
import java.security.InvalidParameterException;
910
import java.security.KeyPair;
@@ -14,15 +15,14 @@
1415
import java.util.logging.Logger;
1516

1617
/**
17-
* All in one example for asymmetric encryption and decryption of a string in one method.
18+
* Example for asymmetric encryption and decryption of a string in one method.
1819
* - Generation of public and private RSA 4096 bit keypair
19-
* - AES-256 authenticated encryption using GCM
2020
* - BASE64 encoding as representation for the byte-arrays
2121
* - UTF-8 encoding of Strings
2222
* - Exception handling
2323
*/
24-
public class ExampleAsymmetricStringEncryptionInOneMethod {
25-
private static final Logger LOGGER = Logger.getLogger(ExampleAsymmetricStringEncryptionInOneMethod.class.getName());
24+
public class ExampleAsymmetricStringEncryption {
25+
private static final Logger LOGGER = Logger.getLogger(ExampleAsymmetricStringEncryption.class.getName());
2626

2727
public static void main(String[] args) {
2828
String plainText = "Text that is going to be sent over an insecure channel and must be encrypted at all costs!";
@@ -37,15 +37,15 @@ public static void main(String[] args) {
3737
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
3838
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
3939

40-
byte[] cipherTextBytes = cipher.doFinal(plainText.getBytes());
40+
byte[] cipherTextBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
4141

4242
// CONVERSION of raw bytes to BASE64 representation
4343
String cipherText = Base64.getEncoder().encodeToString(cipherTextBytes);
4444

4545
// DECRYPTION
4646
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
4747
byte[] decryptedCipherTextBytes = cipher.doFinal(Base64.getDecoder().decode(cipherText));
48-
String decryptedCipherText = new String(decryptedCipherTextBytes);
48+
String decryptedCipherText = new String(decryptedCipherTextBytes,StandardCharsets.UTF_8);
4949

5050
LOGGER.log(Level.INFO, () -> String.format("Decrypted and original plain text are the same: %b", decryptedCipherText.compareTo(plainText) == 0));
5151
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidParameterException e) {

src/main/java/com/cryptoexamples/java/ExampleFileEncryptionInOneMethod.java renamed to src/main/java/com/cryptoexamples/java/ExampleFileEncryption.java

Lines changed: 40 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
package com.cryptoexamples.java;
22

3-
import javax.crypto.*;
3+
import javax.crypto.Cipher;
4+
import javax.crypto.CipherInputStream;
5+
import javax.crypto.CipherOutputStream;
6+
import javax.crypto.KeyGenerator;
7+
import javax.crypto.NoSuchPaddingException;
8+
import javax.crypto.SecretKey;
9+
import javax.crypto.SecretKeyFactory;
410
import javax.crypto.spec.GCMParameterSpec;
511
import javax.crypto.spec.PBEKeySpec;
612
import javax.crypto.spec.SecretKeySpec;
@@ -14,22 +20,26 @@
1420
import java.util.logging.Logger;
1521

1622
/**
17-
* All in one example for encryption and decryption of a file in one method;
18-
* Including
23+
* Example for encryption and decryption of a file in one method.
1924
* - Random password generation using strong secure random number generator
2025
* - Random salt generation
2126
* - Key derivation using PBKDF2 HMAC SHA-512,
2227
* - AES-256 authenticated encryption using GCM
2328
* - BASE64-encoding as representation for the byte-arrays
2429
* - Exception handling
2530
*/
26-
public class ExampleFileEncryptionInOneMethod {
27-
private static final Logger LOGGER = Logger.getLogger(ExampleFileEncryptionInOneMethod.class.getName());
31+
public class ExampleFileEncryption {
32+
private static final Logger LOGGER = Logger.getLogger(ExampleFileEncryption.class.getName());
2833

29-
public static void main(String[] args) {
30-
String plainText = "Multiline text:";
34+
/**
35+
* Demonstrational method that encrypts a file using a password (that is used to derive the required key).
36+
* @param fileName
37+
* @param plainText
38+
* @param password
39+
* @return true if encryption and decryption were successful, false otherwise
40+
*/
41+
public static boolean demonstrateFileEncryption(String fileName, String plainText, String password) {
3142
try {
32-
String password = null;
3343
// GENERATE password (not needed if you have a password already)
3444
if(password == null || password.isEmpty()) {
3545
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
@@ -61,37 +71,42 @@ public static void main(String[] args) {
6171

6272
// SET UP OUTPUT STREAM and write content of String
6373
try (
64-
FileOutputStream fileOutputStream = new FileOutputStream("encryptedFile.enc");
74+
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
6575
CipherOutputStream encryptedOutputStream = new CipherOutputStream(fileOutputStream, cipher);
6676
InputStream stringInputStream = new ByteArrayInputStream(plainText.getBytes(StandardCharsets.UTF_8))
6777
) {
6878
byte[] buffer = new byte[8192];
69-
while (stringInputStream.read(buffer) > 0) {
70-
encryptedOutputStream.write(buffer);
79+
int nread;
80+
while ((nread = stringInputStream.read(buffer)) > 0) {
81+
encryptedOutputStream.write(buffer, 0, nread);
7182
}
83+
encryptedOutputStream.flush();
7284
}
7385

7486
// READ ENCRYPTED FILE
7587
StringBuilder stringBuilder = new StringBuilder();
7688
cipher.init(Cipher.DECRYPT_MODE, key, spec);
77-
89+
String decryptedCipherText;
7890
try (
79-
FileInputStream fileInputStream = new FileInputStream("encryptedFile.enc");
80-
CipherInputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher)
91+
FileInputStream fileInputStream = new FileInputStream(fileName);
92+
CipherInputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher);
93+
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
8194
) {
8295
byte[] buffer = new byte[8192];
83-
while (cipherInputStream.read(buffer) > 0) {
84-
stringBuilder.append(new String(buffer, StandardCharsets.UTF_8));
96+
int nread;
97+
while ((nread = cipherInputStream.read(buffer)) > 0) {
98+
byteArrayOutputStream.write(buffer, 0, nread);
8599
}
100+
byteArrayOutputStream.flush();
101+
decryptedCipherText = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
86102
}
87-
// TODO trim() should not be needed!
88-
String decryptedCipherText = stringBuilder.toString().trim();
89-
LOGGER.log(Level.INFO, decryptedCipherText);
90103

104+
LOGGER.log(Level.INFO, decryptedCipherText);
91105
LOGGER.log(Level.INFO,
92106
() -> String.format("Decrypted file content and original plain text are the same: %b",
93107
decryptedCipherText.compareTo(plainText) == 0)
94108
);
109+
return decryptedCipherText.compareTo(plainText) == 0;
95110
} catch (NoSuchAlgorithmException |
96111
NoSuchPaddingException |
97112
InvalidKeyException |
@@ -100,7 +115,13 @@ public static void main(String[] args) {
100115
InvalidKeySpecException |
101116
IOException e) {
102117
LOGGER.log(Level.SEVERE, e.getLocalizedMessage());
118+
return false;
103119
}
104120
}
105121

122+
123+
public static void main(String[] args) {
124+
demonstrateFileEncryption("encryptedFile.enc","Multiline text:\nMultiline text:\n",null );
125+
}
126+
106127
}

src/main/java/com/cryptoexamples/java/ExampleHashInOneMethod.java renamed to src/main/java/com/cryptoexamples/java/ExampleHash.java

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,21 @@
99
import java.util.logging.Logger;
1010

1111
/**
12-
* All in one example for hashing of a string in one method.
12+
* Example for hashing of a string in one method.
1313
* - SHA-512
1414
* - BASE64 encoding as representation for the byte-arrays
1515
* - UTF-8 encoding of String
1616
* - Exception handling
1717
*/
18-
public class ExampleHashInOneMethod {
19-
private static final Logger LOGGER = Logger.getLogger(ExampleHashInOneMethod.class.getName());
18+
public class ExampleHash {
19+
private static final Logger LOGGER = Logger.getLogger(ExampleHash.class.getName());
2020

21-
public static void main(String[] args) {
22-
String plainText = "Text that should be authenticated by comparing the hash of it!";
21+
/**
22+
* Demonstrational method that hashes the plainText.
23+
* @param plainText
24+
* @return true if hashing was successful, false otherwise
25+
*/
26+
public static boolean demonstrateHash(String plainText) {
2327
try {
2428
// Get MessageDigest Instance
2529
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
@@ -31,8 +35,14 @@ public static void main(String[] args) {
3135
String hashString = Base64.getEncoder().encodeToString(hashBytes);
3236

3337
LOGGER.log(Level.INFO, hashString);
38+
return true;
3439
} catch (NoSuchAlgorithmException e) {
3540
LOGGER.log(Level.SEVERE, e.getLocalizedMessage());
41+
return false;
3642
}
3743
}
44+
45+
public static void main(String[] args) {
46+
demonstrateHash("Text that should be authenticated by comparing the hash of it!");
47+
}
3848
}

0 commit comments

Comments
 (0)