Basic AES/CBC implementation in Java
up vote
0
down vote
favorite
A little bit about myself: I am 18 years old, a student living in Germany and currently working on an android app.
I would like if someone has the time to review my code. I am especially interested if this code has any vulnerabilities and if the efficiency could be improved. Thanks in advance :)
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import java.util.Base64;
public class AES {
public static int iterations = 1000;
private static String seperator = ";";
private static int key_length = 256;
private static int salt_length = 64;
private static final String HASH_ALGORITHM = "PBKDF2WithHmacSHA256";
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
public static void setSaltLength(int length) throws Exception {
if((length > 0) && ((length & (length - 1)) == 0))
salt_length = length;
else
throw new Exception("Invalid Salt Length");
}
public static void setKeyLength(int length) throws Exception {
if(length == 128 || length == 192 || length == 256)
key_length = length;
else
throw new Exception("Invalid Length");
}
public static void setSeperator(String s) throws Exception {
if(seperator.matches("[^+=/\w]"))
seperator = s;
else
throw new Exception("Invalid Seperator");
}
public static void setDurationOnCurrentComputer(int milliseconds){
char password = {'t', 'e', 's', 't'};
int i = 1;
long duration = 0;
while(duration < milliseconds) {
i*=2;
long t = System.currentTimeMillis();
byte salt = new byte[64];
new SecureRandom().nextBytes(salt);
try {
createKey(password, salt, i);
} catch (Exception e) {
e.printStackTrace();
}
duration = System.currentTimeMillis() - t;
System.out.println("i: " + i + " duration: " + duration);
}
iterations = i;
}
private static SecretKey createKey(char password, byte salt, int iterations) throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGORITHM);
KeySpec spec = new PBEKeySpec(password, salt, iterations, key_length);
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), KEY_ALGORITHM);
}
public static String encrypt(char password, byte data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte salt = new byte[salt_length];
new SecureRandom().nextBytes(salt);
cipher.init(Cipher.ENCRYPT_MODE, createKey(password, salt, iterations));
AlgorithmParameters params = cipher.getParameters();
byte iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte ciphertext = cipher.doFinal(data);
Base64.Encoder e = Base64.getEncoder();
return e.encodeToString((e.encodeToString(iv) + seperator + e.encodeToString(ciphertext) + seperator + e.encodeToString(salt)).getBytes());
}
public static String decrypt(char password, String ciphertext) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
Base64.Decoder d = Base64.getDecoder();
String data = new String(d.decode(ciphertext)).split(seperator);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, createKey(password, d.decode(data[2]), iterations), new IvParameterSpec(d.decode(data[0])));
return new String(cipher.doFinal(d.decode(data[1])));
}
}
java aes
New contributor
add a comment |
up vote
0
down vote
favorite
A little bit about myself: I am 18 years old, a student living in Germany and currently working on an android app.
I would like if someone has the time to review my code. I am especially interested if this code has any vulnerabilities and if the efficiency could be improved. Thanks in advance :)
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import java.util.Base64;
public class AES {
public static int iterations = 1000;
private static String seperator = ";";
private static int key_length = 256;
private static int salt_length = 64;
private static final String HASH_ALGORITHM = "PBKDF2WithHmacSHA256";
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
public static void setSaltLength(int length) throws Exception {
if((length > 0) && ((length & (length - 1)) == 0))
salt_length = length;
else
throw new Exception("Invalid Salt Length");
}
public static void setKeyLength(int length) throws Exception {
if(length == 128 || length == 192 || length == 256)
key_length = length;
else
throw new Exception("Invalid Length");
}
public static void setSeperator(String s) throws Exception {
if(seperator.matches("[^+=/\w]"))
seperator = s;
else
throw new Exception("Invalid Seperator");
}
public static void setDurationOnCurrentComputer(int milliseconds){
char password = {'t', 'e', 's', 't'};
int i = 1;
long duration = 0;
while(duration < milliseconds) {
i*=2;
long t = System.currentTimeMillis();
byte salt = new byte[64];
new SecureRandom().nextBytes(salt);
try {
createKey(password, salt, i);
} catch (Exception e) {
e.printStackTrace();
}
duration = System.currentTimeMillis() - t;
System.out.println("i: " + i + " duration: " + duration);
}
iterations = i;
}
private static SecretKey createKey(char password, byte salt, int iterations) throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGORITHM);
KeySpec spec = new PBEKeySpec(password, salt, iterations, key_length);
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), KEY_ALGORITHM);
}
public static String encrypt(char password, byte data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte salt = new byte[salt_length];
new SecureRandom().nextBytes(salt);
cipher.init(Cipher.ENCRYPT_MODE, createKey(password, salt, iterations));
AlgorithmParameters params = cipher.getParameters();
byte iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte ciphertext = cipher.doFinal(data);
Base64.Encoder e = Base64.getEncoder();
return e.encodeToString((e.encodeToString(iv) + seperator + e.encodeToString(ciphertext) + seperator + e.encodeToString(salt)).getBytes());
}
public static String decrypt(char password, String ciphertext) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
Base64.Decoder d = Base64.getDecoder();
String data = new String(d.decode(ciphertext)).split(seperator);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, createKey(password, d.decode(data[2]), iterations), new IvParameterSpec(d.decode(data[0])));
return new String(cipher.doFinal(d.decode(data[1])));
}
}
java aes
New contributor
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
A little bit about myself: I am 18 years old, a student living in Germany and currently working on an android app.
I would like if someone has the time to review my code. I am especially interested if this code has any vulnerabilities and if the efficiency could be improved. Thanks in advance :)
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import java.util.Base64;
public class AES {
public static int iterations = 1000;
private static String seperator = ";";
private static int key_length = 256;
private static int salt_length = 64;
private static final String HASH_ALGORITHM = "PBKDF2WithHmacSHA256";
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
public static void setSaltLength(int length) throws Exception {
if((length > 0) && ((length & (length - 1)) == 0))
salt_length = length;
else
throw new Exception("Invalid Salt Length");
}
public static void setKeyLength(int length) throws Exception {
if(length == 128 || length == 192 || length == 256)
key_length = length;
else
throw new Exception("Invalid Length");
}
public static void setSeperator(String s) throws Exception {
if(seperator.matches("[^+=/\w]"))
seperator = s;
else
throw new Exception("Invalid Seperator");
}
public static void setDurationOnCurrentComputer(int milliseconds){
char password = {'t', 'e', 's', 't'};
int i = 1;
long duration = 0;
while(duration < milliseconds) {
i*=2;
long t = System.currentTimeMillis();
byte salt = new byte[64];
new SecureRandom().nextBytes(salt);
try {
createKey(password, salt, i);
} catch (Exception e) {
e.printStackTrace();
}
duration = System.currentTimeMillis() - t;
System.out.println("i: " + i + " duration: " + duration);
}
iterations = i;
}
private static SecretKey createKey(char password, byte salt, int iterations) throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGORITHM);
KeySpec spec = new PBEKeySpec(password, salt, iterations, key_length);
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), KEY_ALGORITHM);
}
public static String encrypt(char password, byte data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte salt = new byte[salt_length];
new SecureRandom().nextBytes(salt);
cipher.init(Cipher.ENCRYPT_MODE, createKey(password, salt, iterations));
AlgorithmParameters params = cipher.getParameters();
byte iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte ciphertext = cipher.doFinal(data);
Base64.Encoder e = Base64.getEncoder();
return e.encodeToString((e.encodeToString(iv) + seperator + e.encodeToString(ciphertext) + seperator + e.encodeToString(salt)).getBytes());
}
public static String decrypt(char password, String ciphertext) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
Base64.Decoder d = Base64.getDecoder();
String data = new String(d.decode(ciphertext)).split(seperator);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, createKey(password, d.decode(data[2]), iterations), new IvParameterSpec(d.decode(data[0])));
return new String(cipher.doFinal(d.decode(data[1])));
}
}
java aes
New contributor
A little bit about myself: I am 18 years old, a student living in Germany and currently working on an android app.
I would like if someone has the time to review my code. I am especially interested if this code has any vulnerabilities and if the efficiency could be improved. Thanks in advance :)
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import java.util.Base64;
public class AES {
public static int iterations = 1000;
private static String seperator = ";";
private static int key_length = 256;
private static int salt_length = 64;
private static final String HASH_ALGORITHM = "PBKDF2WithHmacSHA256";
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
public static void setSaltLength(int length) throws Exception {
if((length > 0) && ((length & (length - 1)) == 0))
salt_length = length;
else
throw new Exception("Invalid Salt Length");
}
public static void setKeyLength(int length) throws Exception {
if(length == 128 || length == 192 || length == 256)
key_length = length;
else
throw new Exception("Invalid Length");
}
public static void setSeperator(String s) throws Exception {
if(seperator.matches("[^+=/\w]"))
seperator = s;
else
throw new Exception("Invalid Seperator");
}
public static void setDurationOnCurrentComputer(int milliseconds){
char password = {'t', 'e', 's', 't'};
int i = 1;
long duration = 0;
while(duration < milliseconds) {
i*=2;
long t = System.currentTimeMillis();
byte salt = new byte[64];
new SecureRandom().nextBytes(salt);
try {
createKey(password, salt, i);
} catch (Exception e) {
e.printStackTrace();
}
duration = System.currentTimeMillis() - t;
System.out.println("i: " + i + " duration: " + duration);
}
iterations = i;
}
private static SecretKey createKey(char password, byte salt, int iterations) throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGORITHM);
KeySpec spec = new PBEKeySpec(password, salt, iterations, key_length);
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), KEY_ALGORITHM);
}
public static String encrypt(char password, byte data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte salt = new byte[salt_length];
new SecureRandom().nextBytes(salt);
cipher.init(Cipher.ENCRYPT_MODE, createKey(password, salt, iterations));
AlgorithmParameters params = cipher.getParameters();
byte iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte ciphertext = cipher.doFinal(data);
Base64.Encoder e = Base64.getEncoder();
return e.encodeToString((e.encodeToString(iv) + seperator + e.encodeToString(ciphertext) + seperator + e.encodeToString(salt)).getBytes());
}
public static String decrypt(char password, String ciphertext) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
Base64.Decoder d = Base64.getDecoder();
String data = new String(d.decode(ciphertext)).split(seperator);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, createKey(password, d.decode(data[2]), iterations), new IvParameterSpec(d.decode(data[0])));
return new String(cipher.doFinal(d.decode(data[1])));
}
}
java aes
java aes
New contributor
New contributor
New contributor
asked 14 mins ago
user188262
1
1
New contributor
New contributor
add a comment |
add a comment |
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
user188262 is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209763%2fbasic-aes-cbc-implementation-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
user188262 is a new contributor. Be nice, and check out our Code of Conduct.
user188262 is a new contributor. Be nice, and check out our Code of Conduct.
user188262 is a new contributor. Be nice, and check out our Code of Conduct.
user188262 is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209763%2fbasic-aes-cbc-implementation-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown