C's Crypt() like function in Java

I have been reading some codes regarding encrypting a password in Java. Which seems a bit more computing intensive.

Is there a quick way to encrypt a string similar to C or Ruby?

For example, in Ruby:

'hello'.crypt('$6$salt') # => "$6$salt$ghQ6Rhatj/sug12c6v8Ao/bXUoyJ1O1SqdumufgGEO3b3NYPvm/dSWDKWfNm1VxFoFiy/cw9eRaY0xu4GDQSU/"

The method String#crypt() is from C, which is used in Linux to store hashed password in /etc/shadow:

$ sudo cat /etc/shadow | grep $USER
sourav:$6$Vx0wkV1M2PM43WOE$b2pYu.funKjk/snGSqiMTgh1e9dGQYDEKrjfuc2T/tP5qs7lXU56MjFvWd35rgzmYBXK33DrjQqnxTcPtcMXi/:18013:0:99999:7:::

Here's a small program...

Knowing that my system password is 55, in Ruby:

pass = IO.readlines('/etc/shadow').find { |x| x.start_with?(ENV['USER']) }
=> "sourav:$6$Vx0wkV1M2PM43WOE$b2pYu.funKjk/snGSqiMTgh1e9dGQYDEKrjfuc2T/tP5qs7lXU56MjFvWd35rgzmYBXK33DrjQqnxTcPtcMXi/:18013:0:99999:7:::\n"

h = ?$ + pass.split(?$)[1..2].join(?$)
=> "$6$Vx0wkV1M2PM43WOE"

s = pass.split(?$)[-1].split(?:)[0]
=> "b2pYu.funKjk/snGSqiMTgh1e9dGQYDEKrjfuc2T/tP5qs7lXU56MjFvWd35rgzmYBXK33DrjQqnxTcPtcMXi/"

hs = h + ?$ + s
=> "$6$Vx0wkV1M2PM43WOE$b2pYu.funKjk/snGSqiMTgh1e9dGQYDEKrjfuc2T/tP5qs7lXU56MjFvWd35rgzmYBXK33DrjQqnxTcPtcMXi/"

'55'.crypt(h) == hs
=> true

So the system can confirm my password is 55 and let me log in.

Is there a similar method in Java that can encrypt a string? Can I similarly run 'string.crypt("$6$salt")' and decrypt /etc/shadow's account password if the account password is given?

and decrypt /etc/shadow's account password if the account password is given

The crypt() function is not encryption, the function creates a salted password hash.

Hash is a one-way function and one of its primary features is that nobody should be able to recover password based from the (cryptographic) hash value.

So the system can confirm my password is 55 and let me log in.

This is possible. Effectively you compute a new salted hash (using the same salt) and compare with the stored value.

Is there a similar method in Java that can encrypt a string?

import org.apache.commons.codec.digest.Crypt;

...

String hash = Crypt.crypt("password".getBytes());
System.out.println("salted hash: "+hash);
// salt is $X$some_bytes
String salt = hash.substring(0, hash.indexOf("$", 3));
System.out.println("salt: "+salt);
// validation:
String testString = Crypt.crypt("password", salt);
if(testString.equals(hash)) {
  System.out.println("Password match");
} else {
  System.out.println("Invalid password");
}

C Programming Tutorial for Beginners, Learn C the Hard Way: Practical Exercises on the Computational Subjects You Keep Avoiding (Like C) C or c is the third letter in the English and ISO basic Latin alphabets. Its name in English is cee (pronounced / ˈsiː /), plural cees.

Java includes since 1.4 a package named javax.crypto, which allows you to encrypt and decrypt data using a Cipher.

TutorialsPoint has a tutorial for this package. Here is a little Java snippet which first encrypts data, then decrypts it:

public class CipherSample {
 public static void main(String args[]) throws Exception{
  //Creating a Signature object
  Signature sign = Signature.getInstance("SHA256withRSA");

  //Creating KeyPair generator object
  KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

  //Initializing the key pair generator
  keyPairGen.initialize(2048);

  //Generating the pair of keys
  KeyPair pair = keyPairGen.generateKeyPair();      

  //Creating a Cipher object
  Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

  //Initializing a Cipher object
  cipher.init(Cipher.ENCRYPT_MODE, pair.getPublic());

  //Adding data to the cipher
  byte[] input = "Welcome to Tutorialspoint".getBytes();      
  cipher.update(input);

  //encrypting the data
  byte[] cipherText = cipher.doFinal();  
  System.out.println(new String(cipherText, "UTF8"));

  //Initializing the same cipher for decryption
  cipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());

  //Decrypting the text
  byte[] decipheredText = cipher.doFinal(cipherText);
  System.out.println(new String(decipheredText));
  }
}

Not as straightforward, but still simple.

"C" Programming Language: Brian Kernighan, This course will give you a full introduction into all of the core concepts in the C programming Duration: 3:46:13 Posted: Aug 15, 2018 C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. C is the most widely used computer language.

The crypt C library function uses DES as its encryption. You have to use the same algorithm if you want exactly the same result in Java.

In a nutshell:

    KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
    SecretKey desKey = keygenerator.generateKey();

    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

    cipher.init(Cipher.ENCRYPT_MODE, desKey);

    byte[] encrypted = desCipher.doFinal(clearText.getBytes());

You can find a tutorial here: https://www.mkyong.com/java/jce-encryption-data-encryption-standard-des-tutorial/

C Tutorial, "C" is one of the most widely used programming languages of all time. Prof Brian Kernighan Duration: 8:26 Posted: Aug 18, 2015 C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write operating system. The main features of C language include low-level access to memory, simple set of keywords, and clean style, these features make C language suitable for system programming like operating system or compiler development.

Learn C Programming, C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone� This is a list of operators in the C and C++ programming languages.All the operators listed exist in C++; the fourth column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.

Learn C, C is a powerful general-purpose programming language. Our C tutorials will guide you to learn C programming one step at a time with the help of examples. As well as C and Simula's influences, other languages also influenced this new language, including ALGOL 68, Ada, CLU and ML . Initially, Stroustrup's "C with Classes" added features to the C compiler, Cpre, including classes, derived classes, strong typing, inlining and default arguments.

Cprogramming.com: Learn C and C++ Programming, learn-c.org is a free interactive C tutorial for people who want to learn C, fast. Programming Languages Development - C++ has been used extensively in developing new programming languages like C#, Java, JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog etc. Computation Programming - C++ is the best friends of scientists because of fast speed and computational efficiencies.

Comments
  • commons.apache.org/proper/commons-codec/apidocs/org/apache/…
  • Note: byte[] b = s.getBytes("UTF-8"); s = new String(b, "UTF-8"); or StandardCharsets.UTF_8 i.o.` "UTF-8"`.
  • IDK why, but it says error: cannot find symbol I can't import org.apache.commons.codec.digest.Crypt as well, which doesn't exist :(
  • @S.Goswami did you include the commons-codec jar in your buildpath?
  • Ok, so I have included that, and importing import org.apache.commons.codec.digest.Crypt, which seems to work fine. But there's the error of cannot find symbol while using the crypt() from example in the given link...
  • I'm not so sure this does the same thing the crypt function does
  • Even the asking person mixes hash and ciphertext, this answer is wrong an doesn't solve the question (it is even misleading)
  • I don't think this is Crypt(). Before asking the question, I read this on tutorialspoint, and there's a question on stackoverflow regarding cryptography in Java, but they are other algorithms...
  • Not really true, the first number $6$ defines hash algorithm, mode 6 is sha-256