Skip to content

Commit 6c132a4

Browse files
Merge branch 'master' into fix-convex-hull-recursive
2 parents e6bae2c + 71ccf32 commit 6c132a4

36 files changed

Lines changed: 1412 additions & 196 deletions

‎.github/workflows/codeql.yml‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,15 @@ jobs:
3030
distribution: 'temurin'
3131

3232
- name: Initialize CodeQL
33-
uses: github/codeql-action/init@v4.39.3
33+
uses: github/codeql-action/init@v4.39.5
3434
with:
3535
languages: 'java-kotlin'
3636

3737
- name: Build
3838
run: mvn --batch-mode --update-snapshots verify
3939

4040
- name: Perform CodeQL Analysis
41-
uses: github/codeql-action/analyze@v4.39.3
41+
uses: github/codeql-action/analyze@v4.39.5
4242
with:
4343
category: "/language:java-kotlin"
4444

@@ -55,12 +55,12 @@ jobs:
5555
uses: actions/checkout@v7
5656

5757
- name: Initialize CodeQL
58-
uses: github/codeql-action/init@v4.39.3
58+
uses: github/codeql-action/init@v4.39.5
5959
with:
6060
languages: 'actions'
6161

6262
- name: Perform CodeQL Analysis
63-
uses: github/codeql-action/analyze@v4.39.3
63+
uses: github/codeql-action/analyze@v4.39.5
6464
with:
6565
category: "/language:actions"
6666
...

‎src/main/java/com/thealgorithms/backtracking/MazeRecursion.java‎

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,19 @@
66
* ends are marked with different integers.
77
*/
88
public final class MazeRecursion {
9+
private static final int OPEN = 0;
10+
private static final int PATH = 2;
11+
private static final int DEAD_END = 3;
12+
13+
private static final int DEFAULT_START_ROW = 1;
14+
private static final int DEFAULT_START_COLUMN = 1;
15+
private static final int DEFAULT_GOAL_ROW = 6;
16+
private static final int DEFAULT_GOAL_COLUMN = 5;
17+
18+
// Each entry is {rowDelta, colDelta}
19+
// down -> right -> up -> left
920
private static final int[][] FIRST_STRATEGY_DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
21+
// up -> right -> down -> left
1022
private static final int[][] SECOND_STRATEGY_DIRECTIONS = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
1123

1224
private MazeRecursion() {
@@ -21,14 +33,7 @@ private MazeRecursion() {
2133
* @throws IllegalArgumentException if the maze is null, empty, or not rectangular
2234
*/
2335
public static int[][] solveMazeUsingFirstStrategy(int[][] map) {
24-
validateMaze(map);
25-
if (!isInBounds(map, 1, 1) || !isInBounds(map, 6, 5)) {
26-
return null;
27-
}
28-
if (map[6][5] == 2) {
29-
return map;
30-
}
31-
return solve(map, 1, 1, 6, 5, FIRST_STRATEGY_DIRECTIONS) ? map : null;
36+
return solveWithDefaultEndpoints(map, FIRST_STRATEGY_DIRECTIONS);
3237
}
3338

3439
/**
@@ -40,14 +45,7 @@ public static int[][] solveMazeUsingFirstStrategy(int[][] map) {
4045
* @throws IllegalArgumentException if the maze is null, empty, or not rectangular
4146
*/
4247
public static int[][] solveMazeUsingSecondStrategy(int[][] map) {
43-
validateMaze(map);
44-
if (!isInBounds(map, 1, 1) || !isInBounds(map, 6, 5)) {
45-
return null;
46-
}
47-
if (map[6][5] == 2) {
48-
return map;
49-
}
50-
return solve(map, 1, 1, 6, 5, SECOND_STRATEGY_DIRECTIONS) ? map : null;
48+
return solveWithDefaultEndpoints(map, SECOND_STRATEGY_DIRECTIONS);
5149
}
5250

5351
/**
@@ -84,12 +82,23 @@ public static int[][] solveMazeUsingSecondStrategy(int[][] map, int startRow, in
8482
return solve(map, startRow, startColumn, goalRow, goalColumn, SECOND_STRATEGY_DIRECTIONS) ? map : null;
8583
}
8684

85+
private static int[][] solveWithDefaultEndpoints(int[][] map, int[][] directions) {
86+
validateMaze(map);
87+
if (!isInBounds(map, DEFAULT_START_ROW, DEFAULT_START_COLUMN) || !isInBounds(map, DEFAULT_GOAL_ROW, DEFAULT_GOAL_COLUMN)) {
88+
return null;
89+
}
90+
if (map[DEFAULT_GOAL_ROW][DEFAULT_GOAL_COLUMN] == PATH) {
91+
return map;
92+
}
93+
return solve(map, DEFAULT_START_ROW, DEFAULT_START_COLUMN, DEFAULT_GOAL_ROW, DEFAULT_GOAL_COLUMN, directions) ? map : null;
94+
}
95+
8796
private static boolean solve(int[][] map, int row, int column, int goalRow, int goalColumn, int[][] directions) {
88-
if (!isInBounds(map, row, column) || map[row][column] != 0) {
97+
if (!isInBounds(map, row, column) || map[row][column] != OPEN) {
8998
return false;
9099
}
91100

92-
map[row][column] = 2;
101+
map[row][column] = PATH;
93102
if (row == goalRow && column == goalColumn) {
94103
return true;
95104
}
@@ -100,7 +109,7 @@ private static boolean solve(int[][] map, int row, int column, int goalRow, int
100109
}
101110
}
102111

103-
map[row][column] = 3;
112+
map[row][column] = DEAD_END;
104113
return false;
105114
}
106115

‎src/main/java/com/thealgorithms/ciphers/ADFGVXCipher.java‎

Lines changed: 49 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,18 @@ public String encrypt(String plaintext, String key) {
8080
public String decrypt(String ciphertext, String key) {
8181
String fractionatedText = reverseColumnarTransposition(ciphertext, key);
8282

83+
if (fractionatedText.length() % 2 != 0) {
84+
throw new IllegalArgumentException("Invalid ciphertext: odd number of ADFGVX letters.");
85+
}
86+
8387
StringBuilder plaintext = new StringBuilder();
8488
for (int i = 0; i < fractionatedText.length(); i += 2) {
8589
String pair = fractionatedText.substring(i, i + 2);
86-
plaintext.append(POLYBIUS_MAP.get(pair));
90+
Character letter = POLYBIUS_MAP.get(pair);
91+
if (letter == null) {
92+
throw new IllegalArgumentException("Invalid ciphertext: unknown ADFGVX pair \"" + pair + "\".");
93+
}
94+
plaintext.append(letter);
8795
}
8896

8997
return plaintext.toString();
@@ -110,11 +118,7 @@ private String columnarTransposition(String text, String key) {
110118

111119
// Read columns based on the alphabetical order of the key
112120
StringBuilder ciphertext = new StringBuilder();
113-
char[] sortedKey = key.toCharArray();
114-
Arrays.sort(sortedKey);
115-
116-
for (char keyChar : sortedKey) {
117-
int column = key.indexOf(keyChar);
121+
for (int column : columnsInKeyOrder(key)) {
118122
for (char[] row : table) {
119123
if (row[column] != '_') {
120124
ciphertext.append(row[column]);
@@ -125,6 +129,24 @@ private String columnarTransposition(String text, String key) {
125129
return ciphertext.toString();
126130
}
127131

132+
/**
133+
* Returns the column indices in the order the key imposes: alphabetical by
134+
* key letter, with repeated letters ordered by their first occurrence.
135+
* Using key.indexOf for repeated letters would map both occurrences to the
136+
* same column and make the transposition lossy.
137+
*/
138+
private int[] columnsInKeyOrder(String key) {
139+
Integer[] order = new Integer[key.length()];
140+
for (int i = 0; i < order.length; i++) {
141+
order[i] = i;
142+
}
143+
Arrays.sort(order, (a, b) -> {
144+
int byLetter = Character.compare(key.charAt(a), key.charAt(b));
145+
return byLetter != 0 ? byLetter : Integer.compare(a, b);
146+
});
147+
return Arrays.stream(order).mapToInt(Integer::intValue).toArray();
148+
}
149+
128150
/**
129151
* Helper method: Reverses the columnar transposition during decryption
130152
*
@@ -133,31 +155,36 @@ private String columnarTransposition(String text, String key) {
133155
* @return The reversed text
134156
*/
135157
private String reverseColumnarTransposition(String ciphertext, String key) {
136-
int numRows = (int) Math.ceil((double) ciphertext.length() / key.length());
137-
char[][] table = new char[numRows][key.length()];
158+
int numCols = key.length();
159+
int fullRows = ciphertext.length() / numCols;
160+
int remainder = ciphertext.length() % numCols;
161+
// The last row of the encryption table is only partially filled: the
162+
// first `remainder` columns hold one extra character. The previous
163+
// implementation assumed every column had the same length, which
164+
// misaligned the whole grid whenever the length was not a multiple of
165+
// the key length.
166+
int[] columnLength = new int[numCols];
167+
for (int column = 0; column < numCols; column++) {
168+
columnLength[column] = fullRows + (column < remainder ? 1 : 0);
169+
}
138170

139-
char[] sortedKey = key.toCharArray();
140-
Arrays.sort(sortedKey);
171+
int numRows = fullRows + (remainder > 0 ? 1 : 0);
172+
char[][] table = new char[numRows][numCols];
141173

142174
int index = 0;
143175
// Populate the table column by column according to the sorted key
144-
for (char keyChar : sortedKey) {
145-
int column = key.indexOf(keyChar);
146-
for (int row = 0; row < numRows; row++) {
147-
if (index < ciphertext.length()) {
148-
table[row][column] = ciphertext.charAt(index++);
149-
} else {
150-
table[row][column] = '_';
151-
}
176+
for (int column : columnsInKeyOrder(key)) {
177+
for (int row = 0; row < columnLength[column]; row++) {
178+
table[row][column] = ciphertext.charAt(index++);
152179
}
153180
}
154181

155182
// Read the table row by row to reconstruct the fractionated text
156183
StringBuilder fractionatedText = new StringBuilder();
157-
for (char[] row : table) {
158-
for (char cell : row) {
159-
if (cell != '_') {
160-
fractionatedText.append(cell);
184+
for (int row = 0; row < numRows; row++) {
185+
for (int column = 0; column < numCols; column++) {
186+
if (row < columnLength[column]) {
187+
fractionatedText.append(table[row][column]);
161188
}
162189
}
163190
}

‎src/main/java/com/thealgorithms/ciphers/AESEncryption.java‎

Lines changed: 61 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package com.thealgorithms.ciphers;
22

3+
import java.nio.ByteBuffer;
4+
import java.nio.charset.StandardCharsets;
35
import java.security.InvalidAlgorithmParameterException;
46
import java.security.InvalidKeyException;
57
import java.security.NoSuchAlgorithmException;
8+
import java.security.SecureRandom;
69
import javax.crypto.BadPaddingException;
710
import javax.crypto.Cipher;
811
import javax.crypto.IllegalBlockSizeException;
@@ -18,12 +21,15 @@
1821
* underlying bytes.
1922
*/
2023
public final class AESEncryption {
24+
private static final int GCM_IV_LENGTH = 12;
25+
private static final int GCM_TAG_LENGTH = 128;
26+
private static final int MIN_CIPHERTEXT_LENGTH = GCM_IV_LENGTH + GCM_TAG_LENGTH / Byte.SIZE;
27+
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
28+
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
29+
2130
private AESEncryption() {
2231
}
2332

24-
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
25-
private static Cipher aesCipher;
26-
2733
/**
2834
* 1. Generate a plain text for encryption 2. Get a secret key (printed in
2935
* hexadecimal form). In actual use this must be encrypted and kept safe.
@@ -55,34 +61,71 @@ public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException
5561
}
5662

5763
/**
58-
* Encrypts plainText in AES using the secret key
64+
* Encrypts {@code plainText} (UTF-8) with AES-GCM using {@code secKey}.
5965
*
60-
* @return byteCipherText (The encrypted text)
61-
* @throws NoSuchPaddingException (from Cipher)
66+
* <p>Each call generates a fresh 12-byte random IV and uses an explicit 128-bit (16-byte)
67+
* GCM authentication tag. The returned byte array is formatted as
68+
* {@code IV || ciphertext || authentication tag} (a 12-byte IV followed by the ciphertext
69+
* and 16-byte authentication tag).
70+
*
71+
* @param plainText the plaintext string to encrypt
72+
* @param secKey the AES secret key used for encryption
73+
* @return byte array formatted as {@code IV || ciphertext || authentication tag}
6274
* @throws NoSuchAlgorithmException (from Cipher)
75+
* @throws NoSuchPaddingException (from Cipher)
6376
* @throws InvalidKeyException (from Cipher)
64-
* @throws BadPaddingException (from Cipher)
77+
* @throws InvalidAlgorithmParameterException (from Cipher)
6578
* @throws IllegalBlockSizeException (from Cipher)
79+
* @throws BadPaddingException (from Cipher)
6680
*/
67-
public static byte[] encryptText(String plainText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
68-
// AES defaults to AES/ECB/PKCS5Padding in Java 7
69-
aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
70-
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
71-
return aesCipher.doFinal(plainText.getBytes());
81+
public static byte[] encryptText(String plainText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
82+
byte[] iv = new byte[GCM_IV_LENGTH];
83+
SECURE_RANDOM.nextBytes(iv);
84+
85+
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
86+
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
87+
cipher.init(Cipher.ENCRYPT_MODE, secKey, gcmParameterSpec);
88+
byte[] cipherBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
89+
90+
ByteBuffer buffer = ByteBuffer.allocate(iv.length + cipherBytes.length);
91+
buffer.put(iv);
92+
buffer.put(cipherBytes);
93+
return buffer.array();
7294
}
7395

7496
/**
75-
* Decrypts encrypted byte array using the key used for encryption.
97+
* Decrypts a payload formatted as {@code IV || ciphertext || authentication tag} using
98+
* {@code secKey}.
99+
*
100+
* <p>The payload must contain a 12-byte IV followed by the ciphertext and a 16-byte (128-bit)
101+
* GCM authentication tag (at least 28 bytes in total).
76102
*
77-
* @return plainText
103+
* @param byteCipherText encrypted payload formatted as {@code IV || ciphertext || authentication tag}
104+
* @param secKey the AES secret key used during encryption
105+
* @return decrypted UTF-8 plaintext string
106+
* @throws IllegalArgumentException if {@code byteCipherText} is {@code null} or shorter than 28 bytes
107+
* @throws NoSuchAlgorithmException (from Cipher)
108+
* @throws NoSuchPaddingException (from Cipher)
109+
* @throws InvalidKeyException (from Cipher)
110+
* @throws InvalidAlgorithmParameterException (from Cipher)
111+
* @throws IllegalBlockSizeException (from Cipher)
112+
* @throws BadPaddingException if authentication tag verification or decryption fails
78113
*/
79114
public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
80-
// AES defaults to AES/ECB/PKCS5Padding in Java 7
115+
if (byteCipherText == null || byteCipherText.length < MIN_CIPHERTEXT_LENGTH) {
116+
throw new IllegalArgumentException("Ciphertext is too short");
117+
}
118+
ByteBuffer buffer = ByteBuffer.wrap(byteCipherText);
119+
byte[] iv = new byte[GCM_IV_LENGTH];
120+
buffer.get(iv);
121+
byte[] cipherBytes = new byte[buffer.remaining()];
122+
buffer.get(cipherBytes);
123+
81124
Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
82-
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV());
125+
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
83126
decryptionCipher.init(Cipher.DECRYPT_MODE, secKey, gcmParameterSpec);
84-
byte[] bytePlainText = decryptionCipher.doFinal(byteCipherText);
85-
return new String(bytePlainText);
127+
byte[] bytePlainText = decryptionCipher.doFinal(cipherBytes);
128+
return new String(bytePlainText, StandardCharsets.UTF_8);
86129
}
87130

88131
/**

‎src/main/java/com/thealgorithms/ciphers/HillCipher.java‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,14 +68,22 @@ public String decrypt(String message, int[][] inverseKeyMatrix) {
6868
return plainText.toString();
6969
}
7070

71-
// Validates that the determinant of the key matrix is not zero modulo 26
71+
// Validates that the key matrix is invertible modulo 26, which requires the
72+
// determinant to be coprime with 26. Checking only for a zero determinant is not
73+
// enough: a determinant of 2 or 13 (or any other non-unit) passes that check but
74+
// has no inverse, so encryption collapses distinct plaintexts onto the same
75+
// ciphertext and decryption becomes impossible.
7276
private void validateDeterminant(int[][] keyMatrix, int n) {
73-
int det = determinant(keyMatrix, n) % 26;
74-
if (det == 0) {
75-
throw new IllegalArgumentException("Invalid key matrix. Determinant is zero modulo 26.");
77+
int det = Math.floorMod(determinant(keyMatrix, n), 26);
78+
if (gcd(det, 26) != 1) {
79+
throw new IllegalArgumentException("Invalid key matrix. Determinant must be coprime with 26 to be invertible modulo 26.");
7680
}
7781
}
7882

83+
private int gcd(int a, int b) {
84+
return b == 0 ? a : gcd(b, a % b);
85+
}
86+
7987
// Computes the determinant of a matrix recursively
8088
private int determinant(int[][] matrix, int n) {
8189
int det = 0;

‎src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@ public class PlayfairCipher {
66
private String key;
77

88
public PlayfairCipher(String key) {
9-
this.key = key;
9+
// Normalize the key the same way the plaintext is normalized in encrypt():
10+
// uppercase, J folded into I, and non-letters removed. Without this a
11+
// lowercase or mixed-case key, a key containing J, or a key with
12+
// punctuation silently produces a wrong matrix.
13+
this.key = key.toUpperCase().replace("J", "I").replaceAll("[^A-Z]", "");
1014
generateMatrix();
1115
}
1216

‎src/main/java/com/thealgorithms/conversions/OctalToBinary.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ private OctalToBinary() {
3737
*/
3838
public static long convertOctalToBinary(int octalNumber) {
3939
long binaryNumber = 0;
40-
int digitPosition = 1;
40+
long digitPosition = 1;
4141

4242
while (octalNumber != 0) {
4343
int octalDigit = octalNumber % 10;

0 commit comments

Comments
 (0)