1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
|
package security;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class Sample {
public static void main(String[] args) throws Exception {
String password = "12341234@xxxx!'9876";
String msg = "This is the message";
System.out.println("Encrypt '" + msg + "'");
byte[] encrypted = encrypt(msg, password);
System.out.println(bytesToHex(encrypted));
String msg2 = decrypt(encrypted, password);
System.out.println("Descrypt '" + msg2 + "'");
}
public static byte[] encrypt(String message, String password) throws Exception {
SecureRandom rand = new SecureRandom();
byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = new ByteArrayInputStream(messageBytes)) {
byte[] salt = new byte[8];
rand.nextBytes(salt);
out.write(salt);
byte[] derivatedSalt = new byte[8];
rand.nextBytes(derivatedSalt);
out.write(derivatedSalt);
byte[] iv = new byte[16];
rand.nextBytes(iv);
out.write(iv);
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
long length = messageBytes.length;
buffer.putLong(length);
byte[] lengthBytes = buffer.array();
out.write(lengthBytes);
byte[] aesKey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
.generateSecret(new PBEKeySpec(password.toCharArray(), salt, 60000, 256)).getEncoded();
Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
ci.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(iv));
Mac hmac = Mac.getInstance("HmacSHA256");
byte[] key1 = saltedSHA256(saltedSHA256(aesKey, derivatedSalt), derivatedSalt);
hmac.init(new SecretKeySpec(key1, "HmacSHA256"));
hmac.update(iv);
hmac.update(salt);
byte[] ibuf = new byte[8192];
int len;
while ((len = in.read(ibuf)) != -1) {
byte[] obuf = ci.update(ibuf, 0, len);
if (obuf != null) {
out.write(obuf);
hmac.update(ibuf, 0, len);
}
}
byte[] obuf = ci.doFinal();
if (obuf != null) {
out.write(obuf);
}
byte[] bmac = hmac.doFinal();
out.write(bmac);
return out.toByteArray();
}
}
public static String decrypt(byte[] xx, String password) throws Exception {
try (InputStream in = new ByteArrayInputStream(xx);
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
byte[] salt = new byte[8];
read(in, salt);
byte[] derivatedSalt = new byte[8];
read(in, derivatedSalt);
byte[] iv = new byte[16];
read(in, iv);
byte[] lentghBytes = new byte[Long.BYTES];
read(in, lentghBytes);
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.put(lentghBytes);
buffer.flip();// need flip
long length = buffer.getLong();
byte[] aesKey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
.generateSecret(new PBEKeySpec(password.toCharArray(), salt, 60000, 256)).getEncoded();
Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
ci.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(iv));
byte[] key1 = saltedSHA256(saltedSHA256(aesKey, derivatedSalt), derivatedSalt);
Mac hmac = Mac.getInstance("HmacSHA256");
hmac.init(new SecretKeySpec(key1, "HmacSHA256"));
hmac.update(iv);
hmac.update(salt);
long tailleToread = (length / 16 + 1) * 16;
long resteALire = tailleToread;
int bufsize = 8192;
while (resteALire > 0) {
int blockToRead = Math.min((resteALire < bufsize ? (int) resteALire : bufsize + 500), bufsize);
byte[] ibuf = in.readNBytes(blockToRead);
int len = ibuf.length;
resteALire -= len;
byte[] obuf = ci.update(ibuf, 0, len);
if (obuf != null) {
out.write(obuf);
hmac.update(obuf);
}
}
byte[] obuf = ci.doFinal();
if (obuf != null) {
out.write(obuf);
hmac.update(obuf);
}
byte[] bmac = hmac.doFinal();
byte[] readsha = in.readAllBytes();
if (!Arrays.equals(bmac, readsha)) {
throw new Exception("HMAC error");
}
return out.toString(StandardCharsets.UTF_8);
}
}
private static void read(InputStream inputStream, byte[] buffer) throws IOException {
int bufferLength = buffer.length;
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = inputStream.read(buffer, totalBytesRead, bufferLength - totalBytesRead)) != -1) {
totalBytesRead += bytesRead;
if (totalBytesRead == bufferLength) {
break;
}
}
}
private static byte[] saltedSHA256(byte[] data, byte[] salt) throws NoSuchAlgorithmException {
byte[] bytes = new byte[data.length + salt.length];
System.arraycopy(data, 0, bytes, 0, data.length);
System.arraycopy(salt, 0, bytes, data.length, salt.length);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return digest.digest(bytes);
}
public static String bytesToHex(byte[] bytes) {
StringBuilder hexStringBuilder = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
hexStringBuilder.append(String.format("%02x", b));
}
return hexStringBuilder.toString();
}
} |
Partager