How to decrypt encrypted String in C# but encrypted in java (jasypt) - java

i need to decrypt the encrypted string in MsSQl. the encrypted String is encrypted using jasypt as i have the source code (java)
my problem is, i cannot decrypt back the encrypted string in C#.
this is the code used in java:
public String encrypt(String strClearText){
String strKey="password";
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword(strKey);
String encrypted= encryptor.encrypt(strClearText);
return encrypted;
}
I try to convert the jasypt.jar to dll using ikvm and still no luck.
Is there any way i can do to overcome this problem? so that the encrypted password can be use in java and also in c#?
i cannot change the method of encryption as this encrypted String is being used by many other software. i hope you guys can tell me/teach me another way to overcome this problem..
Thank you :)

Related

how decode the encodeBase64URLSafeString hashkey

How to decode the encoded string using encodeBase64URLSafeString.
code:
KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
SecretKey key = generator.generateKey();
encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());
output:
E6S9fTfMfAgkNVodHLDmxz-2M_g90bpFztW6GB7-7VcGfyOkugESxjNx1CGf5taJDXz895uWAF5ubPnaqhe4nw
can anyone please help me on how to decode the output string which is in encrypted format?
Tried using decryption with jasypt library but it is throwing bad input error.
You have to decode it with the same library you have used for encoding org.apache.commons.codec.binary.Base64;
This is working for me
System.out.println(Base64.decodeBase64("E6S9fTfMfAgkNVodHLDmxz-2M_g90bpFztW6GB7-7VcGfyOkugESxjNx1CGf5taJDXz895uWAF5ubPnaqhe4nw"));
Keep in mind Decode/Decrypt are 2 different things. Here you have encoded it, in your last process, so you have to decode it.

Password encryption using google/tink

Good day, I have used google/tink to encrypt a password for storing in a DB using these steps :
// 1. Generate the key material.
KeysetHandle keysetHandle =
KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM);
// 2. Get the primitive.
Aead aead = AeadFactory.getPrimitive(keysetHandle);
// 3. Use the primitive to encrypt a plaintext,
byte[] ciphertext = aead.encrypt(plaintext, aad);
It basically converts password into the bytes, but when i convert it into string to store into the DB, It stores the encrypted password in this format : -�#~�k�D߶{׼�.
But i want to store the password in the format like 11As7737Cs9ue9oo09 using tink encryption.
Is there any way to do it?
Manish, you might not want to encrypt the passwords. You want to hash them. Tink doesn't support password hashing yet, but we can add support if there's enough interest.
Could you please file for a feature request at https://github.com/google/tink/issues/new?
I agree with everyone here that you SHOULD NOT store passwords in the clear.
However, to answer your question because I think it's a common problem when you get some cipher text and the string is unreadable. Say you wanted to store non password data encrypted, and readable. You would need to Base64 encode your cipher text.
When you retrieve your Base64 encoded data back from the database, you would then need to Base64 decode the String and then run it through your decryption process. Building on your example,
String readable = new String(java.util.Base64.getEncoder().encode(cipherText));
byte[] bytesToDecrypt = java.util.Base64.getDecoder().decode(readable.getBytes());

What API and algorithm to be used to encrypt and decrypt a password using java

I am currently creating application using Java, I googled password encryption with java but the results are so enormous I felt overwhelmed. How would I encrypt and decrypt a password using Java? And what is the best practice for encrypting and decrypting passwords? I am guessing MD5 is not a way to go since it is a one way hash. I am using struts2 as my framework, was wondering if they provide password encryption
Updated:
Try JBCrypt:
String password = "MyPassword123";
String hashed = BCrypt.hashpw(password, BCrypt.gensalt(12));
System.out.println(hashed); // $2a$12$QBx3/kI1SAfwBDFOJK1xNOXK8R2yC7vt2yeIYusaqOisYbxTNFiMy
Download jBCrypt-0.3 from here, check README file for more details.
Also I don't recommend to use MD5 because, it's already broken. Instead of that you can use SHA512 it's secure hashing method, you can use MessageDigest. Below code I am using in one of my project, which works perfectly
public String encode(String password, String saltKey)
throws NoSuchAlgorithmException, IOException {
String encodedPassword = null;
byte[] salt = base64ToByte(saltKey);
MessageDigest digest = MessageDigest.getInstance("SHA-512");
digest.reset();
digest.update(salt);
byte[] btPass = digest.digest(password.getBytes("UTF-8"));
for (int i = 0; i < ITERATION_COUNT; i++) {
digest.reset();
btPass = digest.digest(btPass);
}
encodedPassword = byteToBase64(btPass);
return encodedPassword;
}
private byte[] base64ToByte(String str) throws IOException {
BASE64Decoder decoder = new BASE64Decoder();
byte[] returnbyteArray = decoder.decodeBuffer(str);
if (log.isDebugEnabled()) {
log.debug("base64ToByte(String) - end");
}
return returnbyteArray;
}
well, as I know we have following some algorithm to secure password.
MD5 -
PBKDF2 -
SHA -
BCrypt and SCrypt -
among this BCrypt and SCrypt are the more secure way for password security.
There is quite nice project dedicating to solving that problem in Java.
Essentially, it provides two ways of encrypting user passwords:
- MD5
- SHA1
Take a look to the link:
jasypt
for me i see that MD5 its the best way and you don't need to decrypt the password in case the user forgot his password you can give him a way to generate a new one and for the log in you can compare just the hash existing in the data base and the one entred by the user
Always use ONE WAY HASH ALGORITHM.
I would say GO with MD5 hashing. While storing password in DB, use MD5 hashing. So that if you have your password as pass, after hashing it will get stored as asjasdfklasdjf789asdfalsdfashdflasdf (32 character).
As you said, you want to de-crypt the password also. I would say don't do that. While checking the password against DB, what you can do is hash the password and compare that string with what you have in database.
if (DoHashMD5(myPass).equals(rs.getString(2))) {
System.out.print("You are registered user!!!");
} else {
System.out.print("Invalid user!!!");
}
here rs.getString(2) would be your query parameter.

Encrypt in java, decrypt in node.js

I need to encrypt in java and decrypt with node.js. The decryption result is corrupted.
Here is the java code:
public String encrypt(SecretKey key, String message){
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] stringBytes = message.getBytes("UTF8");
byte[] raw = cipher.doFinal(stringBytes);
// converts to base64 for easier display.
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(raw);
return base64;
}
Here is the node.js code:
AEse3SCrypt.decrypt = function(cryptkey, encryptdata) {
encryptdata = new Buffer(encryptdata, 'base64').toString('binary');
var decipher = crypto.createDecipher('aes-128-cbc', cryptkey);
decipher.setAutoPadding(false);
var decoded = decipher.update(encryptdata);
decoded += decipher.final();
return decoded;
}
As a key I use: "[B#4ec6948c"
The jave encrypted result is: "dfGiiHZi8wYBnDetNhneBw=="<br>
The node.js result is garbich....
In java I use "PKCS5Padding". What should be done in node.js regarding padding? I made setAutoPadding(false). If I don't do it I get error decipher fail. (only from node.js version 0.8).
I tried to remove utf8 encoding from the java in order to be complementary with the node.js but it didn't work.
Any idea what is wrong?
As a key I use: "[B#4ec6948c"
That sounds very much like you're just calling toString() on a byte array. That's not giving you the data within the byte array - it's just the default implementation of Object.toString(), called on a byte array.
Try using Arrays.toString(key) to print out the key.
If you were using that broken key value in the node.js code, it's no wonder it's giving you garbage back.
I tried to remove utf8 encoding from the java in order to be complementary with the node.js
That's absolutely the wrong approach. Instead, you should work out how to make the node.js code interpret the plaintext data as UTF-8 encoded text. Fundamentally, strings are character data and encryption acts on binary data - you need a way to bridge the gap, and UTF-8 is an entirely reasonable way of doing so. The initial result of the decryption in node.js should be binary data, which you then "decode" to text via UTF-8.
I'm afraid I don't know enough about the padding side to comment on that.

Create a file protected by a password in java

I would like to create a file protected by a password in JAVA.
What I mean is, once I launch the program, one file created by my program would be directly protected by previously determined password.
Is there an easy way to do it ?
Once again, my aim is not to create a file and then add it a password, but right during the creation protecting the file by a password.
Actually, I want the current runner program not having access in reading/editing the created file EXCEPT if he/she has the password previously set.
So anyway, if some of you know an easy way to protect files when writing them thanks to java, I would be most grateful.
Have a nice day!
You want to encrypt your file('s content) with a password. Here is a pretty well known library to do it: http://www.jasypt.org/
From their site:
..encrypting and decrypting a text...
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword(myEncryptionPassword);
String myEncryptedText = textEncryptor.encrypt(myText);
...
String plainText = textEncryptor.decrypt(myEncryptedText);
You can read/write the encrypted content to your file.
When you want to encrypt files, strings, etc there are 2 main approaches.
You should start by building a class or method to convert ur string/file to an array of bytes. Build another method to convert the array of bytes back to the string/file.
You may encrypt a file using 2 approaches:
1 - Symmetric key - A secret word (usually a huge string of chars or a password set by the user) will encrypt your file and password, and the same password will be used to decrypt.
2 - Asymmetric key - You generate a pair of keys. One is called the public key and the other is called a private key. Public keys are used to encrypt files, private keys to decrypt.
This would be the more 'professional' approach.
If you want a really safe approach, you should download GnuPG. GnuPG is an executable that manages assymmetric encryption, you may build a class to work with GnuPG and let GnuPG manage ur encryption/decryption process.
Theres an unsafe approach that is 'native' to java (symmetric key) that may work out for you:
Encryption:
byte[] key = //... password converted to an array of bytes
byte[] dataToSend = ...
Cipher c = Cipher.getInstance("AES");
SecretKeySpec k =
new SecretKeySpec(key, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
byte[] encryptedData = c.doFinal(dataToSend);
Decryption:
byte[] key = //
byte[] encryptedData = //
Cipher c = Cipher.getInstance("AES");
SecretKeySpec k =
new SecretKeySpec(key, "AES");
c.init(Cipher.DECRYPT_MODE, k);
byte[] data = c.doFinal(encryptedData);
Hope this helps.
If the file is a plain text file, then not giving the user access to the file without a password in your program does not really password-protect the data, because the user can just open the file with some other program. So IF the file is a text file, then I think you must use encryption.
You can use the comment by #mazaneicha to help you get started in this direction. If you want to dive more into it, you can look at the Java Cryptography architectre and the javax.crypto java docs.
If your file is not human-readable, and only your program understands it, then I would make the first line or first n Bytes of the file a password. If you prefer, you could save another password file in the same directory and use that to authenticate the user before deciding if the user has the right to view the file. A common way to encrypt a password is with an MD5 hash function. The user enters a password, you compute the hash of it, then compare the computed hash with the hash value read from the file:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Use to encrypt passwords using MD5 algorithm
* #param password should be a plain text password.
* #return a hex String that results from encrypting the given password.
*/
static String encryptPassword(String password) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte byteData[] = md.digest();
StringBuilder hexString = new StringBuilder();
for (int i=0;i<byteData.length;i++) {
String hex=Integer.toHexString(0xff & byteData[i]);
if(hex.length()==1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
catch(java.security.NoSuchAlgorithmException missing) {
return password;
}
}

Categories

Resources