-2

I have one already created project.

In this they are using one method for encrypting the String. In this project now I have to create a method which I can used for decrypting the encrypted string.

For encrypting a string the below method is used

private String EncryptPwd(String pwd) {
    String encryptPwd = "";
    if (!pwd.isEmpty()) {
        byte[] sha1Bytes = EncryptionUtils.getSha1(pwd);
        StringBuilder sb = new StringBuilder();
        for (byte b : sha1Bytes) {
            sb.append(b);
        }
        encryptPwd = sb.toString();
    }
    return encryptPwd;
}

EncryptionUtils class code is given below

import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.log4j.Logger;

public final class EncryptionUtils {
    private static QueueCacheValueCloner<byte[]> byteArrayCloner = new QueueCacheValueCloner() {
        public byte[] cloneBean(byte[] original) {
            return (byte[]) original.clone();
        }
    };

    private static Logger logger = MiscUtils.getLogger();
    private static final MessageDigest messageDigest = initMessageDigest();
    private static final QueueCache<String, byte[]> sha1Cache = new QueueCache(4, 2048, byteArrayCloner);
    private static final int MAX_SHA_KEY_CACHE_SIZE = 2048;

    private static MessageDigest initMessageDigest() {
        try {
            return MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            logger.error("Error", e);
        }
        return null;
    }

    public static byte[] getSha1(String s) {
        byte[] b = (byte[]) sha1Cache.get(s);
        if (b == null) {
            b = getSha1NoCache(s);
            if (s.length() < 2048) {
                sha1Cache.put(s, b);
            }
        }
        return b;
    }

    protected static byte[] getSha1NoCache(String s) {
    }

    public static SecretKey generateEncryptionKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey;
    }

    public static SecretKeySpec generateEncryptionKey(String seed) {
        byte[] sha1 = getSha1(seed);
        SecretKeySpec secretKey = new SecretKeySpec(sha1, 0, 16, "AES");
        return secretKey;
    }

    public static byte[] encrypt(SecretKey secretKey, byte[] plainData) throws IllegalBlockSizeException,
            BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
        if (secretKey == null) {
            return plainData;
        }
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(1, secretKey);
        byte[] results = cipher.doFinal(plainData);
        return results;
    }

    public static byte[] decrypt(SecretKey secretKey, byte[] encryptedData) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        if (secretKey == null) {
            return encryptedData;
        }
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(2, secretKey);
        byte[] results = cipher.doFinal(encryptedData);
        return results;
    }
}

Now I have to create a method for decrypting the encrypted string.

So can anyone suggest me how can I decrypt a String which is encrypted by above EncryptPwd method.

user3441151
  • 1,880
  • 6
  • 35
  • 79
  • Have you simply used a SHA1 hash on that ? https://stackoverflow.com/questions/2235079/is-it-possible-to-reverse-a-sha1 – Brian Agnew Mar 19 '18 at 13:25
  • Unrelated: learn about java naming conventions - method names go camelCase() - always. And then, when you already have an util class for encrypting things - put "encryptPassword()" there as well, as public method. – GhostCat Mar 19 '18 at 13:26
  • @BrianAgnew How can I use SHA1 for decrypting a encrypted String, Do you have any example? – user3441151 Mar 19 '18 at 13:31
  • 2
    If you "encrypted" your String by simply building it's SHA-1 hash the simple answer is: You can't decrypt it. This is exactly why it's called "Secure Hash Algorithm" because it's one way. – Ben Mar 19 '18 at 13:42
  • Also on an unrelated note: SHA-1 is deprecated since 2011. So you should probably use to a more modern hash. – Ben Mar 19 '18 at 13:44
  • @Ben You can see what I am using for encryption a String. By using `EncryptPwd` method we are encrypting a String. Now I have to create a method for decrypting a encrypted String. – user3441151 Mar 19 '18 at 13:51
  • @user3441151 please read the linked post in my comment above – Brian Agnew Mar 19 '18 at 13:52
  • @BrianAgnew I see that link but did not get anything which can help me, When String is `test123@` then it convert to the encrypted string `-53109131046108677087-3012595126-50-179-75-784111` where I am using `EncryptPwd` method. – user3441151 Mar 19 '18 at 14:07
  • The point is that SHA1 is not an encryption mechanism but a hash mechanism – Brian Agnew Mar 19 '18 at 14:08

2 Answers2

2

Hashing is not encryption. Secure hashing is a one way function that creates output of a certain length indistinguishable from random to an attacker not knowing the original input.

The only way to "reverse" the hash is to test all possible input values. If you find the correct hash then you've found the input, as it is computationally impossible to find two messages that generate the same output value. At least, that used to be the case until Google found a way to create so called SHA-1 collisions using the Shattered attack. This will however not have any effect on strings like password that usually have size and format limitations.

Just hashing the password using SHA-1 is making yourself susceptible to rainbow table attacks. Duplicate passwords can also easily be identified (if there are multiple accounts). Caching the result will also make your password table susceptible to simple timing attacks. Just maybe using a real password hash such as Argon2 and requiring a specific password strength would be a good idea.

The way to verify a password hash is then to perform the same calculation, starting from a given password (salt and work factor) and then compare the result. Decryption doesn't come into it.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
1

SHA1 is a hash function designed in a way that you should not be able to decrypt anything that is "encrypted" (well really it's not encrypted - it's just hash of the message - as suggested in comments) with it (as it's on-directional function)

Instead you can store in your system SHA signature (not original password) and compare the signature (if you know how to generate it).

This has advantage that nobody knows the password (except the user), and you still can verify if he entered it correctly (you just know how to generate SHA from user input, but do not store his password in plain text)

Maciej
  • 1,954
  • 10
  • 14
  • SHA-1 does not *encrypt* at all, it hashes or calculates a message digest. SHA-1 should not be used to perform password hashing directly. So although the gist of your answer is correct, the information around it is not. – Maarten Bodewes Mar 19 '18 at 15:51
  • I agree... I just used "language" from the question... I just said what sha1 is designed for, I do not claim if it's secure or not, as this was not the question. Sometimes you can even retrive hashed word just by googling it's signature (if no seed was used)... – Maciej Mar 19 '18 at 17:29
  • I downvoted for the incorrect terminology. I understand you're putting it in words the OP understands but it's still... Well, incorrect. – Luke Joshua Park Mar 19 '18 at 17:42
  • 1
    Signed is the wrong word to use here. A hash is a hash. Signed refers to digital signature/asymmetric cryptography. – Luke Joshua Park Mar 19 '18 at 19:35