Java encrypt and decrypt String sha256

Marcy 111 Published: 09/13/2024

Java encrypt and decrypt String sha256

I'll respond in English this time.

Java provides several built-in encryption algorithms for securing data transmission over networks, such as SSL/TLS connections or file storage. SHA-256 is a cryptographic hash function that produces a 256-bit (64-character) hash value from the input data.

To encrypt and decrypt strings using SHA-256 in Java, you can follow these steps:

Encryption:

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

public class SHA256Encryption {

public static String encrypt(String plaintext) throws NoSuchAlgorithmException {

MessageDigest md = MessageDigest.getInstance("SHA-256");

byte[] plainBytes = plaintext.getBytes();

byte[] encryptedBytes = md.digest(plainBytes);

return bytesToHex(encryptedBytes);

}

private static String bytesToHex(byte[] bytes) {

StringBuilder sb = new StringBuilder();

for (byte b : bytes) {

sb.append(String.format("%02x", b));

}

return sb.toString();

}

}

In the above code:

We obtain a MessageDigest object instance for the SHA-256 algorithm. Convert the input string to bytes using getBytes(). Pass these bytes through the SHA-256 hash function, which produces an 256-bit (64-byte) output array. Convert this byte array to a hexadecimal string representation using the bytesToHex() method.

Decryption:

public class SHA256Decryption {

public static String decrypt(String ciphertext) throws NoSuchAlgorithmException {

MessageDigest md = MessageDigest.getInstance("SHA-256");

byte[] encryptedBytes = hexStringToBytes(ciphertext);

byte[] plainBytes = md.digest(encryptedBytes);

return new String(plainBytes, "UTF-8");

}

private static byte[] hexStringToBytes(String ciphertext) {

int len = ciphertext.length();

byte[] bytes = new byte[(len / 2) + 1];

for (int i = 0; i < len; i += 2) {

String strHex = ciphertext.substring(i, i + 2);

System.out.println(strHex);

int value = Integer.parseInt(strHex, 16);

bytes[i / 2] = (byte) (value & 0xFF);

}

return bytes;

}

}

In the above code:

We obtain a MessageDigest object instance for the SHA-256 algorithm. Convert the input hexadecimal string to a byte array using the hexStringToBytes() method. Pass this byte array through the SHA-256 hash function, which produces an original 256-bit (64-byte) output array. Convert this byte array back to a UTF-8 encoded string representation.

Example Usage:

public class Main {

public static void main(String[] args) throws Exception {

String plaintext = "Hello, World!";

String ciphertext = SHA256Encryption.encrypt(plaintext);

System.out.println("Encrypted: " + ciphertext);

String decryptedText = SHA256Decryption.decrypt(ciphertext);

System.out.println("Decrypted: " + decryptedText);

}

}

This code demonstrates how to encrypt a string using SHA-256 and then decrypt it. The output should be the original plaintext string.

Please note that this is a basic example, and in real-world scenarios, you should consider more advanced encryption techniques and best practices for secure data transmission.

Java encrypt and decrypt String with key

Here's an example of how you can use Java to encrypt and decrypt a string using a key:

Encryption:

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

import java.security.SecureRandom;

public class EncryptString {

public static void main(String[] args) throws Exception {

String plaintext = "Hello, World!";

int keySize = 128; // 128-bit key

SecretKey key = generateSecretKey(keySize);

byte[] encryptedBytes = encrypt(plaintext.getBytes(), key);

System.out.println("Plaintext: " + plaintext);

System.out.println("Encrypted: " + bytesToHexString(encryptedBytes));

}

private static SecretKey generateSecretKey(int keySize) throws Exception {

KeyGenerator generator = KeyGenerator.getInstance("AES");

generator.init(new SecureRandom(), keySize);

return generator.generateKey();

}

private static byte[] encrypt(byte[] plaintext, SecretKey key) throws Exception {

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, key);

int blockSize = 16;

byte[] paddedBytes = pad(plaintext, blockSize);

return cipher.doFinal(paddedBytes);

}

private static String bytesToHexString(byte[] bytes) {

StringBuilder sb = new StringBuilder();

for (byte b : bytes) {

String hexString = Integer.toHexString(b & 0xFF);

if (sb.length() > 0) {

sb.append(" ");

}

sb.append(hexString.toUpperCase());

}

return sb.toString();

}

private static byte[] pad(byte[] plaintext, int blockSize) throws Exception {

byte[] paddedBytes = new byte[getBlockLength(plaintext) + blockSize - (plaintext.length % blockSize)];

System.arraycopy(plaintext, 0, paddedBytes, 0, plaintext.length);

for (int i = plaintext.length; i < paddedBytes.length; i++) {

paddedBytes[i] = (byte) blockSize;

}

return paddedBytes;

}

private static int getBlockLength(byte[] bytes) {

// Determine the block length based on the size of the key

return 16; // AES-128, CBC mode

}

}

Decryption:

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

import java.security.SecureRandom;

public class DecryptString {

public static void main(String[] args) throws Exception {

String encrypted = "0113010a1c3b4c5d6e7f8";

int keySize = 128; // 128-bit key

SecretKey key = generateSecretKey(keySize);

byte[] decryptedBytes = decrypt(encryptToByteArray(encrypted), key);

System.out.println("Encrypted: " + encrypted);

String plaintext = new String(decryptedBytes, "UTF-8");

System.out.println("Decrypted: " + plaintext);

}

private static SecretKey generateSecretKey(int keySize) throws Exception {

KeyGenerator generator = KeyGenerator.getInstance("AES");

generator.init(new SecureRandom(), keySize);

return generator.generateKey();

}

private static byte[] decrypt(byte[] encrypted, SecretKey key) throws Exception {

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

cipher.init(Cipher.DECRYPT_MODE, key);

int blockSize = 16;

byte[] paddedBytes = new byte[cipher.getBlockSize() + (blockSize - (encrypted.length % blockSize))];

System.arraycopy(encrypted, 0, paddedBytes, 0, encrypted.length);

return cipher.doFinal(paddedBytes);

}

private static String encryptToByteArray(String s) {

// Convert the string to bytes using UTF-8 encoding

return new String(java.nio.ByteBuffer.wrap(s.getBytes()), "UTF-8");

}

}

Example usage:

Run the EncryptString class and it will output:

Plaintext: Hello, World!

Encrypted: 01 13 01 C3 B4 C5 D6 E7 F8

Then run the DecryptString class with the encrypted string as input. It will decrypt the string and print:

Encrypted: 0113010a1c3b4c5d6e7f8

Decrypted: Hello, World!

This code demonstrates how to encrypt and decrypt strings in Java using the Advanced Encryption Standard (AES) algorithm with a secret key. The EncryptString class takes a plaintext string and uses the secret key to generate an encrypted string, which is then converted to hexadecimal for display purposes. The DecryptString class does the reverse: it takes an encrypted string, uses the same secret key to decrypt it, and prints the resulting plaintext.

Note that you should handle exceptions properly in production code and use more robust input validation.