Jump to content

Java Encrypted text shows question marks

Geralt

Hey all apologize in advance for the multiple threads but I'm just curious with my code. Why does the console give me question marks under the HMAC line? Any help would be great! Not trying to spam, just want to know more.

 

Code:

import java.util.Scanner;import javax.crypto.KeyGenerator;import javax.crypto.Mac;import javax.crypto.SecretKey;public class MyMAC {		public static void main(String[] args) {		try {			//get message			Scanner in = new Scanner(System.in);			System.out.print("Enter a string to encrypt: ");			byte[] message = in.nextLine().getBytes("UTF8");						//generate key			KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");			SecretKey key = kg.generateKey();						//get MAC object			Mac mac = Mac.getInstance("HmacSHA1");			mac.init(key);			mac.update(message);			System.out.println("Provider: " + mac.getProvider().getInfo());						//get HMAC			byte[] hmac = mac.doFinal();						//print results			System.out.println("");			System.out.println("MAC: HmacSHA1");			System.out.println("Message: " + new String(message));			System.out.println("HMAC: \"" + new String(hmac, "UTF8") + "\"");						in.close();		} catch (Exception e) {			e.printStackTrace();		}	}}

Output:

Enter a string to encrypt: HelloWorldProvider: SunJCE Provider (implements RSA, DES, Triple DES, AES, Blowfish, ARCFOUR, RC2, PBE, Diffie-Hellman, HMAC)MAC: HmacSHA1Message: HelloWorldHMAC: "?>??J*????????:]?r"

~~~SnapDragon~~~

| CPU: AMD Ryzen 7 3700X @ PBO & -0.06v offset | CPU Cooler: Scythe Ninja 5 |RAM: 32GB G.Skill Flare X 3200MHz @ 3600MHz 1.45V| Mobo: Gigabyte X570 Aorus Elite  | Storage: Crucial MX300 500GB + Western Digital Blue M.2 250GB + Seagate Barracuda 2TB + Western Digital 1TB Blue | Graphics Card: Asus ROG Strix RTX 2070 Super Advanced 8G | Case: Cooler Master HAF X | PSU: Superflower Leadex Silver 650W |

 

Link to comment
Share on other sites

Link to post
Share on other sites

I suspect those characters are not available in the character encoding used in your console, or they are non-printable characters.

Best way to ensure that you can read your binary string as text is to encode it as Base64. That's pretty standard, really. Java will almost certainly have a library that implements it.

 

Also, I am not sure what you are intending to do, but a MAC is not exactly encryption. It is a cryptographicly secure checksum. It allows a message recipient to detect both accidental and malicious modification of data. If it was not cryptographically secure, an attacker could modify the data and simply modify the checksum too so the recipient would be non the wiser.

However you cannot reconstruct the message from a MAC, so it is not really encryption.

 

Then again, I have never used Java Crypto libraries so I may be wrong.

Link to comment
Share on other sites

Link to post
Share on other sites

I suspect those characters are not available in the character encoding used in your console, or they are non-printable characters.

Best way to ensure that you can read your binary string as text is to encode it as Base64. That's pretty standard, really. Java will almost certainly have a library that implements it.

 

Also, I am not sure what you are intending to do, but a MAC is not exactly encryption. It is a cryptographicly secure checksum. It allows a message recipient to detect both accidental and malicious modification of data. If it was not cryptographically secure, an attacker could modify the data and simply modify the checksum too so the recipient would be non the wiser.

However you cannot reconstruct the message from a MAC, so it is not really encryption.

 

Then again, I have never used Java Crypto libraries so I may be wrong.

 

Just as I expected.

 

I did some research and it said that I have to encode and decode it as base64. Previously, we were supposed to import sun.misc.BASE64Encoder. But that has been depreciated and it's now under java.util.base64.

 

Also, yeah I'm a little confused from the crypto classes I had. AES, DES, RSA, HMAC and stuff. Lots of things to cram into my head. Anyways, could you help me with this code? I'm not sure what input is needed. Apparently, it's asking for a <dataFile> or something along those lines.

 

EDIT: Managed to figure it out. They needed a .data file for an input. Updated code is below.

import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.PrivateKey;import java.security.PublicKey;import java.security.SecureRandom;import java.security.Signature;import java.util.Scanner;public class MyCreateSignature {    public static void main(String[] args) {        try {            System.out.print("Enter name of your data file without extention: ");            Scanner in = new Scanner(System.in);                        //generate key pair            KeyPairGenerator kg = KeyPairGenerator.getInstance("DSA", "SUN");            SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");            kg.initialize(1024, random);            KeyPair key = kg.generateKeyPair();            PrivateKey privateKey = key.getPrivate();            PublicKey publicKey = key.getPublic();                        //get signature object            Signature signature = Signature.getInstance("SHA1withDSA", "SUN");            signature.initSign(privateKey);                        //update loop            FileInputStream dataFis = new FileInputStream("Signature Files\\" + in.nextLine() + ".data");            System.out.println("Creating Signature...");            BufferedInputStream dataBis = new BufferedInputStream(dataFis);            byte[] dataBuffer = new byte[1024];                        int length;                        while (dataBis.available() != 0) {                length = dataBis.read(dataBuffer);                signature.update(dataBuffer, 0, length);            }            dataBis.close();                        //create signature and signature file            byte[] SignatureBytes = signature.sign();            FileOutputStream signatureFos = new FileOutputStream("Signature Files\\mySignature.sig");            signatureFos.write(SignatureBytes);            new sun.misc.BASE64Encoder().encode(SignatureBytes, signatureFos);            signatureFos.close();            System.out.println("Signature saved to mySignature.sig:");            System.out.println(new sun.misc.BASE64Encoder().encode(SignatureBytes) + "\n");                        //create public key file            byte[] encodedPublicKeyBytes = publicKey.getEncoded();            FileOutputStream publicKeyFos = new FileOutputStream("Signature Files\\myPublicKey.pk");            publicKeyFos.write(encodedPublicKeyBytes);            new sun.misc.BASE64Encoder().encode(encodedPublicKeyBytes);            publicKeyFos.close();            System.out.println("Public key saved to myPublicKey.pk:");            System.out.println(new sun.misc.BASE64Encoder().encode(encodedPublicKeyBytes) + "\n");        } catch (Exception e) {            e.printStackTrace();        }    }}

~~~SnapDragon~~~

| CPU: AMD Ryzen 7 3700X @ PBO & -0.06v offset | CPU Cooler: Scythe Ninja 5 |RAM: 32GB G.Skill Flare X 3200MHz @ 3600MHz 1.45V| Mobo: Gigabyte X570 Aorus Elite  | Storage: Crucial MX300 500GB + Western Digital Blue M.2 250GB + Seagate Barracuda 2TB + Western Digital 1TB Blue | Graphics Card: Asus ROG Strix RTX 2070 Super Advanced 8G | Case: Cooler Master HAF X | PSU: Superflower Leadex Silver 650W |

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×