Ejemplos de Criptografía Android Java

Ejemplos de criptografía Android Java incluyendo cálculo de hash, encriptación AES y codificación Base64

💻 Codificación Base64 java

🟢 simple ⭐⭐

Codificar y decodificar datos usando Base64 con varias opciones y conjuntos de caracteres

⏱️ 20 min 🏷️ java, android, base64, encoding
Prerequisites: Basic Java
// Android Java Base64 Encoding Examples
// Using java.util.Base64 (Android API 26+) and android.util.Base64

import java.util.Base64;
import android.util.Base64 as AndroidBase64;
import java.nio.charset.StandardCharsets;
import java.io.*;

// 1. Basic Base64 Encoding/Decoding
class BasicBase64 {

    // Encode string to Base64
    public String encodeToString(String input) {
        byte[] encodedBytes = Base64.getEncoder().encode(input.getBytes());
        return new String(encodedBytes);
    }

    // Decode Base64 to string
    public String decodeString(String encoded) {
        byte[] decodedBytes = Base64.getDecoder().decode(encoded);
        return new String(decodedBytes);
    }

    // Encode bytes to Base64
    public String encodeBytes(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    // Decode Base64 to bytes
    public byte[] decodeToBytes(String encoded) {
        return Base64.getDecoder().decode(encoded);
    }

    // Encode with URL-safe mode
    public String encodeUrlSafe(String input) {
        return Base64.getUrlEncoder().encodeToString(input.getBytes());
    }

    // Decode URL-safe Base64
    public String decodeUrlSafe(String encoded) {
        byte[] decodedBytes = Base64.getUrlDecoder().decode(encoded);
        return new String(decodedBytes);
    }
}

// 2. Android Base64 (Compat for older API levels)
class AndroidBase64Codec {

    // Encode using Android Base64
    public String encode(String input, int flags) {
        byte[] inputBytes = input.getBytes(StandardCharsets.UTF_8);
        byte[] encoded = AndroidBase64.encode(inputBytes, flags);
        return new String(encoded);
    }

    public String encode(String input) {
        return encode(input, AndroidBase64.NO_WRAP);
    }

    // Decode using Android Base64
    public String decode(String encoded, int flags) {
        byte[] decoded = AndroidBase64.decode(encoded, flags);
        return new String(decoded, StandardCharsets.UTF_8);
    }

    public String decode(String encoded) {
        return decode(encoded, AndroidBase64.NO_WRAP);
    }

    // Encode with NO_WRAP (no padding)
    public String encodeNoWrap(String input) {
        return encode(input, AndroidBase64.NO_WRAP);
    }

    // Encode with CRLF (line breaks)
    public String encodeWithCRLF(String input) {
        return encode(input, AndroidBase64.CRLF);
    }
}

// 3. Base64 for Binary Data
class BinaryBase64 {

    // Encode image to Base64
    public String encodeImage(byte[] imageBytes) {
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    // Decode Base64 to image bytes
    public byte[] decodeToImage(String encoded) {
        return Base64.getDecoder().decode(encoded);
    }

    // Encode file to Base64
    public String encodeFile(File file) throws IOException {
        byte[] bytes = readBytesFromFile(file);
        return Base64.getEncoder().encodeToString(bytes);
    }

    // Decode Base64 and save to file
    public boolean decodeToFile(String encoded, File file) {
        try {
            byte[] bytes = Base64.getDecoder().decode(encoded);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.close();
            return true;
        } catch (Exception e) {
            System.out.println("Error decoding to file: " + e.getMessage());
            return false;
        }
    }

    // Encode with MIME encoding (76 chars per line)
    public String encodeMime(String input) {
        return Base64.getMimeEncoder().encodeToString(input.getBytes());
    }

    // Decode MIME encoding
    public String decodeMime(String encoded) {
        byte[] decodedBytes = Base64.getMimeDecoder().decode(encoded);
        return new String(decodedBytes);
    }

    private byte[] readBytesFromFile(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        byte[] bytes = new byte[(int) file.length()];
        fis.read(bytes);
        fis.close();
        return bytes;
    }
}

// 4. Base64 Streams
class Base64Streams {

    // Encode large file with streaming
    public boolean encodeLargeFile(File inputFile, File outputFile) {
        try {
            FileInputStream inputStream = new FileInputStream(inputFile);
            FileOutputStream outputStream = new FileOutputStream(outputFile);
            java.io.OutputStream encoder = Base64.getEncoder().wrap(outputStream);

            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                encoder.write(buffer, 0, bytesRead);
            }

            encoder.close();
            inputStream.close();

            return true;
        } catch (Exception e) {
            System.out.println("Error encoding large file: " + e.getMessage());
            return false;
        }
    }

    // Decode large file with streaming
    public boolean decodeLargeFile(File inputFile, File outputFile) {
        try {
            FileInputStream inputStream = new FileInputStream(inputFile);
            FileOutputStream outputStream = new FileOutputStream(outputFile);
            java.io.InputStream decoder = Base64.getDecoder().wrap(inputStream);

            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = decoder.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            decoder.close();
            outputStream.close();

            return true;
        } catch (Exception e) {
            System.out.println("Error decoding large file: " + e.getMessage());
            return false;
        }
    }
}

// 5. Base64 Validation and Utilities
class Base64Utilities {

    // Validate Base64 string
    public boolean isValidBase64(String input) {
        try {
            Base64.getDecoder().decode(input);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    // Check if URL-safe Base64
    public boolean isValidUrlSafeBase64(String input) {
        try {
            Base64.getUrlDecoder().decode(input);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    // Remove padding from Base64
    public String removePadding(String encoded) {
        return encoded.replaceAll("=+$", "");
    }

    // Add padding to Base64
    public String addPadding(String encoded) {
        int paddingLength = (4 - (encoded.length() % 4)) % 4;
        StringBuilder sb = new StringBuilder(encoded);
        for (int i = 0; i < paddingLength; i++) {
            sb.append('=');
        }
        return sb.toString();
    }

    // Convert standard Base64 to URL-safe
    public String toUrlSafe(String encoded) {
        return encoded
            .replace("+", "-")
            .replace("/", "_")
            .replaceAll("=+$", "");
    }

    // Convert URL-safe to standard Base64
    public String fromUrlSafe(String encoded) {
        String result = encoded
            .replace("-", "+")
            .replace("_", "/");

        // Add padding
        int paddingLength = (4 - (result.length() % 4)) % 4;
        StringBuilder sb = new StringBuilder(result);
        for (int i = 0; i < paddingLength; i++) {
            sb.append('=');
        }

        return sb.toString();
    }
}

// 6. Base64 for Data URLs
class DataUrlBase64 {

    // Create data URL for image
    public String createImageDataUrl(byte[] imageBytes, String mimeType) {
        String base64 = Base64.getEncoder().encodeToString(imageBytes);
        return "data:" + mimeType + ";base64," + base64;
    }

    public String createImageDataUrl(byte[] imageBytes) {
        return createImageDataUrl(imageBytes, "image/png");
    }

    // Create data URL for text
    public String createTextDataUrl(String text, String mimeType) {
        String base64 = Base64.getEncoder().encodeToString(text.getBytes());
        return "data:" + mimeType + ";base64," + base64;
    }

    public String createTextDataUrl(String text) {
        return createTextDataUrl(text, "text/plain");
    }

    // Extract Base64 from data URL
    public String extractFromDataUrl(String dataUrl) {
        String prefix = "base64,";
        int index = dataUrl.indexOf(prefix);

        if (index != -1) {
            return dataUrl.substring(index + prefix.length());
        }

        return null;
    }

    // Parse data URL
    public DataUrlPair parseDataUrl(String dataUrl) {
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("data:([^;]+);base64,(.+)");
        java.util.regex.Matcher matcher = pattern.matcher(dataUrl);

        if (matcher.find()) {
            String mimeType = matcher.group(1);
            String base64 = matcher.group(2);
            return new DataUrlPair(mimeType, base64);
        }

        return null;
    }

    static class DataUrlPair {
        public String mimeType;
        public String base64;

        public DataUrlPair(String mimeType, String base64) {
            this.mimeType = mimeType;
            this.base64 = base64;
        }
    }
}

// 7. Base64 Hash and Checksum
class Base64Hash {

    // Encode MD5 hash as Base64
    public String md5Base64(String input) throws Exception {
        java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        byte[] hash = digest.digest(input.getBytes());
        return Base64.getEncoder().encodeToString(hash);
    }

    // Encode SHA-256 hash as Base64
    public String sha256Base64(String input) throws Exception {
        java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(input.getBytes());
        return Base64.getEncoder().encodeToString(hash);
    }

    // Create Basic Authentication header
    public String createBasicAuth(String username, String password) {
        String credentials = username + ":" + password;
        String encoded = Base64.getEncoder().encodeToString(credentials.getBytes());
        return "Basic " + encoded;
    }

    // Parse Basic Authentication
    public BasicAuthPair parseBasicAuth(String header) {
        if (!header.startsWith("Basic ")) {
            return null;
        }

        String encoded = header.substring(6);
        String decoded = new String(Base64.getDecoder().decode(encoded));

        String[] parts = decoded.split(":", 2);
        if (parts.length == 2) {
            return new BasicAuthPair(parts[0], parts[1]);
        }

        return null;
    }

    static class BasicAuthPair {
        public String username;
        public String password;

        public BasicAuthPair(String username, String password) {
            this.username = username;
            this.password = password;
        }
    }
}

// Main demonstration
public class Base64EncodingDemo {
    public static void demonstrateBase64Encoding() throws Exception {
        System.out.println("=== Android Java Base64 Encoding Examples ===\n");

        // 1. Basic encoding/decoding
        System.out.println("--- 1. Basic Encoding/Decoding ---");
        BasicBase64 basicBase64 = new BasicBase64();

        String text = "Hello, World!";
        String encoded = basicBase64.encodeToString(text);
        System.out.println("Original: " + text);
        System.out.println("Encoded: " + encoded);

        String decoded = basicBase64.decodeString(encoded);
        System.out.println("Decoded: " + decoded);

        // 2. URL-safe encoding
        System.out.println("\n--- 2. URL-Safe Encoding ---");
        String urlText = "Hello, World! This is a test.";

        String urlEncoded = basicBase64.encodeUrlSafe(urlText);
        System.out.println("URL-safe encoded: " + urlEncoded);

        String urlDecoded = basicBase64.decodeUrlSafe(urlEncoded);
        System.out.println("URL-safe decoded: " + urlDecoded);

        // 3. Binary data
        System.out.println("\n--- 3. Binary Data ---");
        BinaryBase64 binaryBase64 = new BinaryBase64();

        byte[] imageData = new byte[]{(byte) 0x89, (byte) 0x50, (byte) 0x4E,
            (byte) 0x47, (byte) 0x0D, (byte) 0x0A}; // PNG header
        String imageEncoded = binaryBase64.encodeImage(imageData);
        System.out.println("Image data encoded: " + imageEncoded);

        byte[] imageDecoded = binaryBase64.decodeToImage(imageEncoded);
        StringBuilder hex = new StringBuilder();
        for (byte b : imageDecoded) {
            hex.append(String.format("0x%02X ", b));
        }
        System.out.println("Image data decoded: " + hex.toString().trim());

        // 4. MIME encoding
        System.out.println("\n--- 4. MIME Encoding ---");
        String longText = "This is a very long text that will be split into " +
            "multiple lines when using MIME encoding.";

        String mimeEncoded = binaryBase64.encodeMime(longText);
        System.out.println("MIME encoded:");
        System.out.println(mimeEncoded);

        // 5. Utilities
        System.out.println("\n--- 5. Utilities ---");
        Base64Utilities utilities = new Base64Utilities();

        System.out.println("Is valid Base64: " + utilities.isValidBase64(encoded));
        System.out.println("Is valid URL-safe: " + utilities.isValidUrlSafeBase64(urlEncoded));

        String withPadding = "SGVsbG8=";
        System.out.println("\nRemove padding: " + utilities.removePadding(withPadding));
        System.out.println("Add padding: " + utilities.addPadding(utilities.removePadding(withPadding)));

        String standardBase64 = "SGVsbG8rV29ybGQvVGVzdA==";
        String urlSafe = utilities.toUrlSafe(standardBase64);
        System.out.println("\nTo URL-safe: " + urlSafe);
        System.out.println("From URL-safe: " + utilities.fromUrlSafe(urlSafe));

        // 6. Data URLs
        System.out.println("\n--- 6. Data URLs ---");
        DataUrlBase64 dataUrl = new DataUrlBase64();

        byte[] textBytes = "Sample text".getBytes();
        String textDataUrl = dataUrl.createTextDataUrl(new String(textBytes), "text/plain");
        System.out.println("Text data URL: " + textDataUrl);

        String extracted = dataUrl.extractFromDataUrl(textDataUrl);
        System.out.println("Extracted Base64: " + extracted);

        // 7. Hash and authentication
        System.out.println("\n--- 7. Hash and Authentication ---");
        Base64Hash base64Hash = new Base64Hash();

        String md5Base64 = base64Hash.md5Base64(text);
        System.out.println("MD5 Base64: " + md5Base64);

        String sha256Base64 = base64Hash.sha256Base64(text);
        System.out.println("SHA-256 Base64: " + sha256Base64);

        String basicAuth = base64Hash.createBasicAuth("alice", "password123");
        System.out.println("\nBasic Auth: " + basicAuth);

        Base64Hash.BasicAuthPair parsedAuth = base64Hash.parseBasicAuth(basicAuth);
        System.out.println("Parsed Auth: " + parsedAuth.username + " / " + parsedAuth.password);

        System.out.println("\n=== All Base64 Encoding Examples Completed ===");
    }
}

💻 Cálculo de Hash java

🟡 intermediate ⭐⭐⭐⭐

Calcular hashes MD5, SHA-1, SHA-256 y SHA-512 para cadenas y archivos

⏱️ 30 min 🏷️ java, android, cryptography, hash
Prerequisites: Intermediate Java, Cryptography basics
// Android Java Hash Calculation Examples
// Using java.security package

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.SecureRandom;

// 1. String Hashing
class StringHasher {

    // Calculate MD5 hash
    public String md5(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] hash = digest.digest(input.getBytes());
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 not available", e);
        }
    }

    // Calculate SHA-1 hash
    public String sha1(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            byte[] hash = digest.digest(input.getBytes());
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-1 not available", e);
        }
    }

    // Calculate SHA-256 hash
    public String sha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes());
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 not available", e);
        }
    }

    // Calculate SHA-512 hash
    public String sha512(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-512");
            byte[] hash = digest.digest(input.getBytes());
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-512 not available", e);
        }
    }

    // Calculate with salt
    public String hashWithSalt(String input, String salt, String algorithm) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            digest.update(salt.getBytes());
            byte[] hash = digest.digest(input.getBytes());
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(algorithm + " not available", e);
        }
    }

    public String hashWithSalt(String input, String salt) {
        return hashWithSalt(input, salt, "SHA-256");
    }

    // Helper: Convert bytes to hex string
    private String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    // Helper: Convert bytes to hex string (alternative)
    private String bytesToHexAlternative(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }
}

// 2. File Hashing
class FileHasher {

    // Calculate hash for file
    public String hashFile(File file, String algorithm) throws IOException {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);

            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                digest.update(buffer, 0, bytesRead);
            }
            fis.close();

            byte[] hash = digest.digest();
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(algorithm + " not available", e);
        }
    }

    public String hashFile(File file) throws IOException {
        return hashFile(file, "SHA-256");
    }

    // Calculate MD5 of file
    public String md5File(File file) throws IOException {
        return hashFile(file, "MD5");
    }

    // Calculate SHA-256 of file
    public String sha256File(File file) throws IOException {
        return hashFile(file, "SHA-256");
    }

    // Calculate hash for large file with progress
    public interface HashProgressListener {
        void onProgress(long bytesProcessed, long totalBytes);
    }

    public String hashFileWithProgress(
            File file,
            String algorithm,
            HashProgressListener listener
    ) throws IOException {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            long fileSize = file.length();
            long bytesProcessed = 0L;

            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                digest.update(buffer, 0, bytesRead);
                bytesProcessed += bytesRead;
                if (listener != null) {
                    listener.onProgress(bytesProcessed, fileSize);
                }
            }
            fis.close();

            byte[] hash = digest.digest();
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(algorithm + " not available", e);
        }
    }

    public String hashFileWithProgress(File file, String algorithm) throws IOException {
        return hashFileWithProgress(file, algorithm, null);
    }

    private String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    // Verify file integrity
    public boolean verifyFileIntegrity(File file, String expectedHash, String algorithm) throws IOException {
        String actualHash = hashFile(file, algorithm);
        return actualHash.equalsIgnoreCase(expectedHash);
    }

    public boolean verifyFileIntegrity(File file, String expectedHash) throws IOException {
        return verifyFileIntegrity(file, expectedHash, "SHA-256");
    }
}

// 3. Password Hashing
class PasswordHasher {

    // Simple password hash (not for production - use bcrypt/argon2 instead)
    public String hashPassword(String password, String salt) {
        StringHasher hasher = new StringHasher();
        return hasher.hashWithSalt(password, salt, "SHA-256");
    }

    // Generate random salt
    public String generateSalt(int length) {
        byte[] bytes = new byte[length];
        new SecureRandom().nextBytes(bytes);
        return bytesToHex(bytes);
    }

    public String generateSalt() {
        return generateSalt(32);
    }

    private String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    // Hash with iterations (slow hash)
    public String hashWithIterations(String password, String salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = (password + salt).getBytes();

            for (int i = 0; i < iterations; i++) {
                hash = digest.digest(hash);
            }

            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 not available", e);
        }
    }

    public String hashWithIterations(String password, String salt) {
        return hashWithIterations(password, salt, 10000);
    }

    // Verify password
    public boolean verifyPassword(String password, String salt, String expectedHash) {
        String actualHash = hashWithIterations(password, salt, 10000);
        return actualHash.equalsIgnoreCase(expectedHash);
    }
}

// 4. HMAC (Hash-based Message Authentication Code)
class HmacHasher {

    // Calculate HMAC-SHA256
    public String hmacSha256(String data, String key) {
        try {
            javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256");
            javax.crypto.spec.SecretKeySpec secretKey =
                new javax.crypto.spec.SecretKeySpec(key.getBytes(), "HmacSHA256");
            mac.init(secretKey);
            byte[] hmac = mac.doFinal(data.getBytes());
            return bytesToHex(hmac);
        } catch (Exception e) {
            throw new RuntimeException("HMAC-SHA256 failed", e);
        }
    }

    // Calculate HMAC-SHA512
    public String hmacSha512(String data, String key) {
        try {
            javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA512");
            javax.crypto.spec.SecretKeySpec secretKey =
                new javax.crypto.spec.SecretKeySpec(key.getBytes(), "HmacSHA512");
            mac.init(secretKey);
            byte[] hmac = mac.doFinal(data.getBytes());
            return bytesToHex(hmac);
        } catch (Exception e) {
            throw new RuntimeException("HMAC-SHA512 failed", e);
        }
    }

    // Verify HMAC
    public boolean verifyHmac(String data, String key, String expectedHmac, String algorithm) {
        String actualHmac;
        if ("HmacSHA256".equals(algorithm)) {
            actualHmac = hmacSha256(data, key);
        } else if ("HmacSHA512".equals(algorithm)) {
            actualHmac = hmacSha512(data, key);
        } else {
            throw new IllegalArgumentException("Unsupported algorithm: " + algorithm);
        }
        return actualHmac.equalsIgnoreCase(expectedHmac);
    }

    public boolean verifyHmac(String data, String key, String expectedHmac) {
        return verifyHmac(data, key, expectedHmac, "HmacSHA256");
    }

    private String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }
}

// 5. Hash Comparison and Utilities
class HashUtilities {

    // Compare two hashes securely (prevent timing attacks)
    public boolean secureCompare(String hash1, String hash2) {
        return MessageDigest.isEqual(hash1.getBytes(), hash2.getBytes());
    }

    // Generate hash for checksum file
    public String generateChecksum(File file) throws IOException {
        FileHasher hasher = new FileHasher();
        return hasher.sha256File(file);
    }

    // Create checksum file content
    public String createChecksumContent(File file) throws IOException {
        String hash = new FileHasher().sha256File(file);
        return hash + "  " + file.getName();
    }

    // Parse checksum file
    public java.util.Map<String, String> parseChecksumFile(File checksumFile) throws IOException {
        java.util.Map<String, String> checksums = new java.util.HashMap<>();

        BufferedReader reader = new BufferedReader(new java.io.FileReader(checksumFile));
        String line;
        while ((line = reader.readLine()) != null) {
            String[] parts = line.split("  ", 2);
            if (parts.length == 2) {
                checksums.put(parts[1], parts[0]);
            }
        }
        reader.close();

        return checksums;
    }

    // Verify checksums from file
    public boolean verifyChecksums(File directory, File checksumFile) throws IOException {
        java.util.Map<String, String> checksums = parseChecksumFile(checksumFile);
        FileHasher hasher = new FileHasher();

        for (java.util.Map.Entry<String, String> entry : checksums.entrySet()) {
            String filename = entry.getKey();
            String expectedHash = entry.getValue();

            File file = new File(directory, filename);
            if (!file.exists()) {
                System.out.println("File not found: " + filename);
                return false;
            }

            String actualHash = hasher.sha256File(file);
            if (!actualHash.equalsIgnoreCase(expectedHash)) {
                System.out.println("Checksum mismatch for " + filename);
                return false;
            }
        }

        return true;
    }
}

// 6. Hash-based Operations
class HashBasedOperations {

    // Generate hash-based identifier
    public String generateIdentifier(String input) {
        String hash = new StringHasher().sha256(input);
        return hash.substring(0, 16);
    }

    // Create content-based hash for deduplication
    public String contentHash(String content) {
        return new StringHasher().sha256(content);
    }

    // Hash-based cache key
    public String createCacheKey(java.util.Map<String, Object> params) {
        java.util.List<String> pairs = new java.util.ArrayList<>();
        java.util.List<String> keys = new java.util.ArrayList<>(params.keySet());
        java.util.Collections.sort(keys);

        for (String key : keys) {
            pairs.add(key + "=" + params.get(key));
        }

        String paramString = android.text.TextUtils.join("&", pairs);
        return new StringHasher().sha256(paramString);
    }

    // Hash-based URL shortener (simplified)
    public String shortenUrl(String url) {
        String hash = new StringHasher().md5(url);
        return hash.substring(0, 8);
    }

    // Bloom filter hash functions
    public java.util.List<Integer> bloomFilterHashes(String item, int numHashes, int filterSize) {
        java.util.List<Integer> hashes = new java.util.ArrayList<>();
        String hash1 = new StringHasher().sha256(item);
        String hash2 = new StringHasher().md5(item);

        for (int i = 0; i < numHashes; i++) {
            String combined = hash1 + hash2 + i;
            String hash = new StringHasher().sha256(combined);
            int index = (Integer.parseInt(hash.substring(0, 8), 16) % filterSize);
            hashes.add(index);
        }

        return hashes;
    }
}

// Main demonstration
public class HashCalculationDemo {
    public static void demonstrateHashCalculation() {
        System.out.println("=== Android Java Hash Calculation Examples ===\n");

        // 1. String hashing
        System.out.println("--- 1. String Hashing ---");
        StringHasher stringHasher = new StringHasher();

        String text = "Hello, World!";
        System.out.println("Text: " + text);
        System.out.println("MD5: " + stringHasher.md5(text));
        System.out.println("SHA-1: " + stringHasher.sha1(text));
        System.out.println("SHA-256: " + stringHasher.sha256(text));
        System.out.println("SHA-512: " + stringHasher.sha512(text));

        // Hash with salt
        String salt = "random_salt_123";
        System.out.println("\nHashed with salt '" + salt + "':");
        System.out.println(stringHasher.hashWithSalt(text, salt));

        // 2. Password hashing
        System.out.println("\n--- 2. Password Hashing ---");
        PasswordHasher passwordHasher = new PasswordHasher();

        String password = "SecurePassword123!";
        String generatedSalt = passwordHasher.generateSalt();

        System.out.println("Password: " + password);
        System.out.println("Generated salt: " + generatedSalt);

        String hashedPassword = passwordHasher.hashWithIterations(password, generatedSalt, 10000);
        System.out.println("Hashed password: " + hashedPassword);

        boolean isValid = passwordHasher.verifyPassword(password, generatedSalt, hashedPassword);
        System.out.println("Password verification: " + isValid);

        // 3. HMAC
        System.out.println("\n--- 3. HMAC ---");
        HmacHasher hmacHasher = new HmacHasher();

        String data = "Important message";
        String key = "secret_key";

        String hmac = hmacHasher.hmacSha256(data, key);
        System.out.println("Data: " + data);
        System.out.println("HMAC-SHA256: " + hmac);

        boolean hmacVerified = hmacHasher.verifyHmac(data, key, hmac);
        System.out.println("HMAC verification: " + hmacVerified);

        // 4. File hashing
        System.out.println("\n--- 4. File Hashing ---");
        System.out.println("File hashing methods:");
        System.out.println("  - hashFile(): Calculate hash for any file");
        System.out.println("  - md5File(): Calculate MD5 of file");
        System.out.println("  - sha256File(): Calculate SHA-256 of file");
        System.out.println("  - hashFileWithProgress(): Track progress for large files");
        System.out.println("  - verifyFileIntegrity(): Verify file against expected hash");

        // 5. Hash utilities
        System.out.println("\n--- 5. Hash Utilities ---");
        HashUtilities hashUtils = new HashUtilities();

        String hash1 = "abc123";
        String hash2 = "abc123";
        String hash3 = "xyz789";

        System.out.println("Secure compare 'abc123' vs 'abc123': " + hashUtils.secureCompare(hash1, hash2));
        System.out.println("Secure compare 'abc123' vs 'xyz789': " + hashUtils.secureCompare(hash1, hash3));

        // 6. Hash-based operations
        System.out.println("\n--- 6. Hash-Based Operations ---");
        HashBasedOperations hashOps = new HashBasedOperations();

        String identifier = hashOps.generateIdentifier("unique_item_123");
        System.out.println("Generated identifier: " + identifier);

        java.util.Map<String, Object> params = new java.util.HashMap<>();
        params.put("user", "alice");
        params.put("page", 1);
        params.put("limit", 20);

        String cacheKey = hashOps.createCacheKey(params);
        System.out.println("Cache key: " + cacheKey);

        String shortUrl = hashOps.shortenUrl("https://example.com/very/long/url/path");
        System.out.println("Shortened URL: " + shortUrl);

        java.util.List<Integer> bloomHashes = hashOps.bloomFilterHashes("test_item", 3, 1000);
        System.out.println("Bloom filter hashes: " + bloomHashes);

        System.out.println("\n=== All Hash Calculation Examples Completed ===");
    }
}

💻 Encriptación AES java

🔴 complex ⭐⭐⭐⭐⭐

Encriptar y desencriptar datos usando AES con varios modos y esquemas de relleno

⏱️ 40 min 🏷️ java, android, cryptography, encryption
Prerequisites: Advanced Java, Cryptography knowledge
// Android Java AES Encryption Examples
// Using javax.crypto package

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.io.*;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;

// Encryption result holder
class EncryptionResult {
    public String iv;
    public String cipherText;

    public EncryptionResult(String iv, String cipherText) {
        this.iv = iv;
        this.cipherText = cipherText;
    }
}

// PBE encryption result holder
class PbeEncryptionResult {
    public String salt;
    public String iv;
    public String cipherText;

    public PbeEncryptionResult(String salt, String iv, String cipherText) {
        this.salt = salt;
        this.iv = iv;
        this.cipherText = cipherText;
    }
}

// 1. Basic AES Encryption
class BasicAesEncryption {

    // Generate AES key
    public SecretKey generateKey(int keySize) throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(keySize);
        return keyGen.generateKey();
    }

    public SecretKey generateKey() throws Exception {
        return generateKey(256);
    }

    // Encrypt with AES/GCM/NoPadding
    public EncryptionResult encryptGCM(String plainText, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

        // Generate random IV
        byte[] iv = new byte[12];
        new SecureRandom().nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

        byte[] cipherText = cipher.doFinal(plainText.getBytes());

        // Return IV and ciphertext as Base64
        String ivBase64 = Base64.getEncoder().encodeToString(iv);
        String cipherTextBase64 = Base64.getEncoder().encodeToString(cipherText);

        return new EncryptionResult(ivBase64, cipherTextBase64);
    }

    // Decrypt with AES/GCM/NoPadding
    public String decryptGCM(String cipherText, String iv, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

        byte[] ivBytes = Base64.getDecoder().decode(iv);
        byte[] cipherTextBytes = Base64.getDecoder().decode(cipherText);

        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);

        byte[] plainText = cipher.doFinal(cipherTextBytes);
        return new String(plainText);
    }

    // Encrypt with AES/CBC/PKCS5Padding
    public EncryptionResult encryptCBC(String plainText, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // Generate random IV (16 bytes for CBC)
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

        byte[] cipherText = cipher.doFinal(plainText.getBytes());

        String ivBase64 = Base64.getEncoder().encodeToString(iv);
        String cipherTextBase64 = Base64.getEncoder().encodeToString(cipherText);

        return new EncryptionResult(ivBase64, cipherTextBase64);
    }

    // Decrypt with AES/CBC/PKCS5Padding
    public String decryptCBC(String cipherText, String iv, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        byte[] ivBytes = Base64.getDecoder().decode(iv);
        byte[] cipherTextBytes = Base64.getDecoder().decode(cipherText);

        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);

        byte[] plainText = cipher.doFinal(cipherTextBytes);
        return new String(plainText);
    }
}

// 2. Password-Based Encryption
class PasswordBasedEncryption {

    // Derive key from password
    public SecretKey deriveKeyFromPassword(
            String password,
            byte[] salt,
            int keySize,
            int iterations
    ) throws Exception {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

        KeySpec spec = new PBEKeySpec(
            password.toCharArray(),
            salt,
            iterations,
            keySize
        );

        SecretKey tmp = factory.generateSecret(spec);
        return new SecretKeySpec(tmp.getEncoded(), "AES");
    }

    public SecretKey deriveKeyFromPassword(String password, byte[] salt) throws Exception {
        return deriveKeyFromPassword(password, salt, 256, 65536);
    }

    // Generate random salt
    public byte[] generateSalt(int size) {
        byte[] salt = new byte[size];
        new SecureRandom().nextBytes(salt);
        return salt;
    }

    public byte[] generateSalt() {
        return generateSalt(16);
    }

    // Encrypt with password
    public PbeEncryptionResult encryptWithPassword(String plainText, String password) throws Exception {
        byte[] salt = generateSalt();
        SecretKey key = deriveKeyFromPassword(password, salt);

        BasicAesEncryption aes = new BasicAesEncryption();
        EncryptionResult result = aes.encryptGCM(plainText, key);

        String saltBase64 = Base64.getEncoder().encodeToString(salt);

        return new PbeEncryptionResult(saltBase64, result.iv, result.cipherText);
    }

    // Decrypt with password
    public String decryptWithPassword(
            String cipherText,
            String iv,
            String salt,
            String password
    ) throws Exception {
        byte[] saltBytes = Base64.getDecoder().decode(salt);
        SecretKey key = deriveKeyFromPassword(password, saltBytes);

        BasicAesEncryption aes = new BasicAesEncryption();
        return aes.decryptGCM(cipherText, iv, key);
    }

    // Generate key with specific iterations
    public SecretKey generateStrongKey(String password, int iterations) throws Exception {
        byte[] salt = generateSalt();
        return deriveKeyFromPassword(password, salt, 256, iterations);
    }

    public SecretKey generateStrongKey(String password) throws Exception {
        return generateStrongKey(password, 100000);
    }
}

// 3. File Encryption
class FileEncryption {

    // Encrypt file
    public boolean encryptFile(
            File inputFile,
            File outputFile,
            SecretKey key
    ) {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

            byte[] iv = new byte[12];
            new SecureRandom().nextBytes(iv);
            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

            // Write IV first
            FileOutputStream fos = new FileOutputStream(outputFile);
            fos.write(iv);

            // Encrypt file content
            FileInputStream fis = new FileInputStream(inputFile);
            CipherOutputStream cipherStream = new CipherOutputStream(fos, cipher);

            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                cipherStream.write(buffer, 0, bytesRead);
            }

            cipherStream.close();
            fis.close();

            return true;
        } catch (Exception e) {
            System.out.println("Error encrypting file: " + e.getMessage());
            return false;
        }
    }

    // Decrypt file
    public boolean decryptFile(
            File inputFile,
            File outputFile,
            SecretKey key
    ) {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

            // Read IV first
            FileInputStream fis = new FileInputStream(inputFile);
            byte[] iv = new byte[12];
            fis.read(iv);

            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);

            // Decrypt file content
            FileOutputStream fos = new FileOutputStream(outputFile);
            CipherInputStream cipherStream = new CipherInputStream(fis, cipher);

            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = cipherStream.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

            cipherStream.close();
            fos.close();

            return true;
        } catch (Exception e) {
            System.out.println("Error decrypting file: " + e.getMessage());
            return false;
        }
    }
}

// 4. String Encryption Utilities
class StringEncryptionUtils {

    private BasicAesEncryption aes = new BasicAesEncryption();
    private PasswordBasedEncryption passwordEnc = new PasswordBasedEncryption();

    // Encrypt string to Base64 (combined IV + ciphertext)
    public String encryptStringToBase64(String plainText, String password) throws Exception {
        PbeEncryptionResult result = passwordEnc.encryptWithPassword(plainText, password);

        // Combine salt + iv + ciphertext
        String combined = result.salt + ":" + result.iv + ":" + result.cipherText;
        return Base64.getEncoder().encodeToString(combined.getBytes());
    }

    // Decrypt string from Base64
    public String decryptStringFromBase64(String encoded, String password) throws Exception {
        String combined = new String(Base64.getDecoder().decode(encoded));
        String[] parts = combined.split(":", 3);

        if (parts.length != 3) {
            throw new IllegalArgumentException("Invalid encrypted format");
        }

        return passwordEnc.decryptWithPassword(parts[2], parts[1], parts[0], password);
    }
}

// 5. Advanced AES Operations
class AdvancedAesOperations {

    // Encrypt with custom IV
    public String encryptWithCustomIV(String plainText, SecretKey key, byte[] iv) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

        byte[] cipherText = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(cipherText);
    }

    // Encrypt with AES-ECB (not recommended for production)
    public String encryptECB(String plainText, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] cipherText = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(cipherText);
    }

    // Decrypt with AES-ECB
    public String decryptECB(String cipherText, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);

        byte[] cipherTextBytes = Base64.getDecoder().decode(cipherText);
        byte[] plainText = cipher.doFinal(cipherTextBytes);

        return new String(plainText);
    }

    // Generate AES key from bytes
    public SecretKey keyFromBytes(byte[] keyBytes) {
        if (keyBytes.length != 16 && keyBytes.length != 24 && keyBytes.length != 32) {
            throw new IllegalArgumentException("Key must be 16, 24, or 32 bytes");
        }
        return new SecretKeySpec(keyBytes, "AES");
    }

    // Generate AES key from password (simple version)
    public SecretKey keyFromPassword(String password, int keySize) {
        byte[] keyBytes = new byte[keySize / 8];
        byte[] passwordBytes = password.getBytes();

        System.arraycopy(passwordBytes, 0, keyBytes, 0,
            Math.min(passwordBytes.length, keyBytes.length));

        return keyFromBytes(keyBytes);
    }

    public SecretKey keyFromPassword(String password) {
        return keyFromPassword(password, 256);
    }
}

// 6. Secure Key Management
class KeyManager {

    // Store key securely (simplified - Android Keystore requires more setup)
    public boolean storeKeyInKeystore(String alias, SecretKey key) {
        // Note: Full Android Keystore integration requires additional setup
        // This is a simplified example
        try {
            // In production, use AndroidKeyStore with proper configuration
            System.out.println("Key '" + alias + "' would be stored in Android Keystore");
            return true;
        } catch (Exception e) {
            System.out.println("Error storing key: " + e.getMessage());
            return false;
        }
    }

    // Load key from keystore (simplified)
    public SecretKey loadKeyFromKeystore(String alias) {
        // In production, load from Android Keystore
        System.out.println("Key '" + alias + "' would be loaded from Android Keystore");
        return null;
    }

    // Generate and store key
    public SecretKey generateAndStoreKey(String alias, int keySize) throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(keySize);
        SecretKey key = keyGen.generateKey();

        if (storeKeyInKeystore(alias, key)) {
            return key;
        } else {
            return null;
        }
    }

    public SecretKey generateAndStoreKey(String alias) throws Exception {
        return generateAndStoreKey(alias, 256);
    }
}

// Main demonstration
public class AesEncryptionDemo {
    public static void demonstrateAesEncryption() throws Exception {
        System.out.println("=== Android Java AES Encryption Examples ===\n");

        // 1. Basic encryption
        System.out.println("--- 1. Basic AES Encryption ---");
        BasicAesEncryption aes = new BasicAesEncryption();

        SecretKey key = aes.generateKey(256);
        System.out.println("Generated AES key: " + key.getAlgorithm());

        String plainText = "This is a secret message!";
        System.out.println("Plaintext: " + plainText);

        EncryptionResult gcmResult = aes.encryptGCM(plainText, key);
        System.out.println("\nEncrypted with AES/GCM:");
        System.out.println("IV: " + gcmResult.iv);
        System.out.println("Ciphertext: " + gcmResult.cipherText);

        String decrypted = aes.decryptGCM(gcmResult.cipherText, gcmResult.iv, key);
        System.out.println("\nDecrypted: " + decrypted);

        // 2. CBC mode
        System.out.println("\n--- 2. CBC Mode ---");
        EncryptionResult cbcResult = aes.encryptCBC(plainText, key);
        System.out.println("Encrypted with AES/CBC:");
        System.out.println("Ciphertext: " + cbcResult.cipherText);

        String decryptedCbc = aes.decryptCBC(cbcResult.cipherText, cbcResult.iv, key);
        System.out.println("Decrypted: " + decryptedCbc);

        // 3. Password-based encryption
        System.out.println("\n--- 3. Password-Based Encryption ---");
        PasswordBasedEncryption passwordEnc = new PasswordBasedEncryption();

        String password = "SecurePassword123!";
        PbeEncryptionResult pbeResult = passwordEnc.encryptWithPassword(plainText, password);

        System.out.println("Encrypted with password:");
        System.out.println("Salt: " + pbeResult.salt);
        System.out.println("Ciphertext: " + pbeResult.cipherText);

        String decryptedPbe = passwordEnc.decryptWithPassword(
            pbeResult.cipherText,
            pbeResult.iv,
            pbeResult.salt,
            password
        );
        System.out.println("Decrypted: " + decryptedPbe);

        // 4. String utilities
        System.out.println("\n--- 4. String Encryption Utilities ---");
        StringEncryptionUtils stringUtils = new StringEncryptionUtils();

        String base64Encrypted = stringUtils.encryptStringToBase64("Hello, World!", password);
        System.out.println("Base64 encrypted: " + base64Encrypted);

        String base64Decrypted = stringUtils.decryptStringFromBase64(base64Encrypted, password);
        System.out.println("Decrypted: " + base64Decrypted);

        // 5. Advanced operations
        System.out.println("\n--- 5. Advanced Operations ---");
        AdvancedAesOperations advancedOps = new AdvancedAesOperations();

        byte[] customIv = new byte[16];
        new SecureRandom().nextBytes(customIv);

        String customEncrypted = advancedOps.encryptWithCustomIV(plainText, key, customIv);
        System.out.println("Encrypted with custom IV: " + customEncrypted);

        // Note: File encryption requires actual files
        System.out.println("\n--- 6. File Encryption ---");
        System.out.println("File encryption methods:");
        System.out.println("  - encryptFile(): Encrypt entire file");
        System.out.println("  - decryptFile(): Decrypt encrypted file");

        // 7. Key management
        System.out.println("\n--- 7. Key Management ---");
        KeyManager keyManager = new KeyManager();
        System.out.println("Key management methods:");
        System.out.println("  - generateAndStoreKey(): Generate and store in Android Keystore");
        System.out.println("  - loadKeyFromKeystore(): Load stored key");
        System.out.println("  - keyFromBytes(): Create key from byte array");
        System.out.println("  - keyFromPassword(): Derive key from password");

        System.out.println("\n=== All AES Encryption Examples Completed ===");
    }
}