Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

How to encrypt and decrypt an integer in Java

1 Answer

0 votes
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import java.util.Base64;

public class IntegerEncryption {
    public static void main(String[] args) throws Exception {
        int number = 123456;

        // Convert integer to string
        String numberString = Integer.toString(number);

        // Generate Advanced Encryption Standard (AES) key
        // AES = symmetric-key algorithm = the same key is used for both encrypting and decrypting the data
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); // 128-bit encryption
        SecretKey secretKey = keyGen.generateKey();

        // Encrypt the integer
        String encryptedNumber = encrypt(numberString, secretKey);

        // Decrypt the integer
        String decryptedNumber = decrypt(encryptedNumber, secretKey);

        System.out.println("Original Number: " + number);
        System.out.println("Encrypted: " + encryptedNumber);
        System.out.println("Decrypted: " + decryptedNumber);
    }

    // Encryption method
    public static String encrypt(String data, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // Decryption method
    public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        
        return new String(decryptedBytes);
    }
}


/*
run:

Original Number: 123456
Encrypted: Ru0jY/KcTYP1T/tf1fSLHA==
Decrypted: 123456

*/

 



answered Mar 22, 2025 by avibootz
...