I have imported this library http://raginggoblin.wordpress.com/2012/08/11/java-alternative-to-php-crypt-function/, in to my project but yet unable to use the class named "crypt" to encrypt string by passing password and salt to crypt method in it.
public class JavaApplication6 {
public static void main(String[] args) {
// TODO code application logic here
String password = "rasmuslerdorf";
String salt = "$6$rounds=5000$usesomesillystringforsalt$";
String encrypted = Crypt.crypt(password, salt);
System.out.println(""+encrypted);
}
}
this is the imported library contains,
Based on your posted code, I suspect you aren't getting the correct Crypt. I suggest you use a static import and change this,
String encrypted = Crypt.crypt(password, salt);
to
String encrypted = crypt(password, salt);
or you might use,
String encrypted = raging.goblin.crypt.Crypt.crypt(password, salt);
And the static import would be,
static import raging.goblin.crypt.Crypt.crypt;
Finally your image tells me you got the src jar, the way you're using it you want the binary jar.
Related
I need some guidance on the scenario where I need to check the password coming from UI form (i.e, Authentication object) which I need to hashed using SHA-256 + constant salt(before making comparison) and password coming from DB (DB also has hashed password + salt) using Spring Security.
I am looking to compare these two different hashed value generated using same SALT value. How we can do it in java? Could anyone please share me a sample code?
You could simply compare the two password strings passwordA.equals(passwordB) ...
This has some security shortcomings:
Passwords should not be handled as strings, but as char or byte arrays: see here why
An Equal comparison is (theoretically) vulnerable to a timing-attack: see a discussion about a solution in java
It might be wise to use standard-tool to do security related things (even when they seem to be simple). Spring security has a ton of tools that can do that for you. Have a look at BCryptPasswordEncoder for example. Using well tested and maintained frameworks for security purposes is always a good idea.
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(password);
...
boolean result = passwordEncoder.matches(rawPassword, hashedPassword);
Also: Use a proper Algorithm for Password-Hashing! See this Answer on SO for some proposals
SHA-256 is not one of them. Spring Security gives you the right tools for the jobs, so you could just use them.
It looks to me you're looking to compare two separate hashed values created using same salt. Am I right ? If yes, so here is the sample program taking a reference from https://ashishpshukla.wordpress.com/2010/07/02/sample-java-code-for-password-encryption-using-secure-hash-algorithm-sha-256/
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class PasswordEncoder {
private static PasswordEncoder instance;
private final static int ITERATION_COUNT = 5;
private PasswordEncoder() { }
public static synchronized PasswordEncoder getInstance() {
if (instance == null) {
PasswordEncoder returnPasswordEncoder = new PasswordEncoder();
return returnPasswordEncoder;
}
else
return instance;
}
public synchronized String encode(String password, String saltKey)throws NoSuchAlgorithmException, IOException {
String encodedPassword = null;
byte[] salt = base64ToByte(saltKey);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
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);
return returnbyteArray;
}
private String byteToBase64(byte[] bt) {
BASE64Encoder endecoder = new BASE64Encoder();
String returnString = endecoder.encode(bt);
return returnString;
}
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
String password = "Secrete#343";
String saltKey = "PveFT7isDjGYFTaYhc2Fzw==";
String hash1,hash2 = null;
// Assume from UI
PasswordEncoder encoder1 = PasswordEncoder.getInstance();
hash1 = encoder1.encode(password, saltKey);
System.out.println(hash1);
// Assume the same present in db
PasswordEncoder encoder2 = PasswordEncoder.getInstance();
hash2 = encoder2.encode(password, saltKey);
System.out.println(hash2);
if(hash1.equalsIgnoreCase(hash2))
System.out.println("Both hash Matches..");
else
System.out.println("Hash matches fails..");
}
}
The output:
8WgbLik5EbdtJY4OWm2ZQ0tHiU2lmvXNVrPhFDz3W2Y=
8WgbLik5EbdtJY4OWm2ZQ0tHiU2lmvXNVrPhFDz3W2Y=
Both hash Matches..
I am using BasicTextEncryptor Class to text encryption and decryption text.
While executing the class file I am getting an exception
Exception in thread "main" org.jasypt.exceptions.EncryptionOperationNotPossibleException: Encryption raised an exception. A possible cause is you are using strong encryption algorithms and you have not installed the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files in this Java Virtual Machine
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.handleInvalidKeyException(StandardPBEByteEncryptor.java:1073)
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.encrypt(StandardPBEByteEncryptor.java:924)
at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.encrypt(StandardPBEStringEncryptor.java:642)
at org.jasypt.util.text.StrongTextEncryptor.encrypt(StrongTextEncryptor.java:107)
at com.newposition.util.TestJascrypt.main(TestJascrypt.java:45)
I have refer some of the solution blog but still not able to sorted out the issue.
I have copied the policy jar file in the /jre/lib/security/.
Nut still I am getting the exception.
Can any one please help me.
Below is my encryptor class.
package com.myproject.util;
import java.io.IOException;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.util.binary.BasicBinaryEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.jasypt.util.text.StrongTextEncryptor;
public class TestJascrypt {
public static StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
public static BasicBinaryEncryptor binaryEncryptor = new BasicBinaryEncryptor();
public static void main(String []sene) throws IOException{
StrongTextEncryptor textEncryptor = new StrongTextEncryptor();
textEncryptor.setPassword("abcd");
String myEncryptedText = textEncryptor.encrypt("abcd");
String plainText = textEncryptor.decrypt(myEncryptedText);
System.out.println(plainText +" ##############");
}
}
Thanks in advance.
I am working on an application that uploads a file to amazon s3(part of the application). But when I generate the URL of the files, it shows the authentication key, file name and etc. I need to encrypt the URL. Also I am using tiny url to shorten the URL but when I put the curser on the link it shows the real URL. I looked for md5 but I couldn't make it work. Is there any suggestion?
I will try to explain how MD5 works
import java.math.*;
import java.security.*;
public class testMain {
/**
* #param args
*/
public static void main(String[] args) {
String stringThatNeedsToBeEncrpyted = "yourURL"; // Value to encrypt
MessageDigest mdEnc = null;
try {
mdEnc = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Encryption algorithm
mdEnc.update(stringThatNeedsToBeEncrpyted.getBytes(), 0, stringThatNeedsToBeEncrpyted.length());
String md5 = new BigInteger(1, mdEnc.digest()).toString(16); //Make the Encrypted string
System.out.println(md5); //print the string in the console
}
}
The output is : 7f5976785d03c60f9fd4b08fb78e72ce
This is your message digest.
EDIT
Hashing a username and password should always be done with an appropriate hashing algorithm like PBKDF2, bcrypt or scrypt. Furthermore always use SSL to transfer confidential data.
Currently, the only way I know to retrieve the administrator password from a newly created EC2 windows instance is through the AWS management console. This is fine, but I need to know how to accomplish this via the Java API - I can't seem to find anything on the subject. Also, once obtained, how do I modify the password using the same API?
The EC2 API has a call "GetPasswordData" which you can use to retrieve an encrypted block of data containing the Administrator password. To decrypt it, you need 2 things:
First, the private key. This is the private half of the keypair you used to instantiate the instance. A complication is that normally Amazon uses keys in PEM format ("-----BEGIN"...) but the Java Crypto API wants keys in DER format. You can do the conversion yourself - strip off the -----BEGIN and -----END lines, take the block of text in the middle and base64-decode it.
Second, the encryption parameters. The data is encrypted with RSA, with PKCS1 padding – so the magic invocation to give to JCE is: Cipher.getInstance("RSA/NONE/PKCS1Padding")
Here's a full example (that relies on BouncyCastle, but could be modified to use a different crypto engine)
package uk.co.frontiertown;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.GetPasswordDataRequest;
import com.amazonaws.services.ec2.model.GetPasswordDataResult;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import javax.crypto.Cipher;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
public class GetEc2WindowsAdministratorPassword {
private static final String ACCESS_KEY = "xxxxxxxxxxxxxxxxxxxx";
private static final String SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private static final String PRIVATE_KEY_MATERIAL = "-----BEGIN RSA PRIVATE KEY-----\n" +
"MIIEowIBAAKCAQEAjdD54kJ88GxkeRc96EQPL4h8c/7V2Q2QY5VUiJ+EblEdcVnADRa12qkohT4I\n" +
// several more lines of key data
"srz+xXTvbjIJ6RL/FDqF8lvWEvb8uSC7GeCMHTznkicwUs0WiFax2AcK3xjgtgQXMgoP\n" +
"-----END RSA PRIVATE KEY-----\n";
public static void main(String[] args) throws GeneralSecurityException, InterruptedException {
Security.addProvider(new BouncyCastleProvider());
String password = getPassword(ACCESS_KEY, SECRET_KEY, "i-XXXXXXXX", PRIVATE_KEY_MATERIAL);
System.out.println(password);
}
private static String getPassword(String accessKey, String secretKey, String instanceId, String privateKeyMaterial) throws GeneralSecurityException, InterruptedException {
// Convert the private key in PEM format to DER format, which JCE can understand
privateKeyMaterial = privateKeyMaterial.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
privateKeyMaterial = privateKeyMaterial.replace("-----END RSA PRIVATE KEY-----", "");
byte[] der = Base64.decode(privateKeyMaterial);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(der);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
// Get the encrypted password data from EC2
AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonEC2Client client = new AmazonEC2Client(awsCredentials);
GetPasswordDataRequest getPasswordDataRequest = new GetPasswordDataRequest().withInstanceId(instanceId);
GetPasswordDataResult getPasswordDataResult = client.getPasswordData(getPasswordDataRequest);
String passwordData = getPasswordDataResult.getPasswordData();
while (passwordData == null || passwordData.isEmpty()) {
System.out.println("No password data - probably not generated yet - waiting and retrying");
Thread.sleep(10000);
getPasswordDataResult = client.getPasswordData(getPasswordDataRequest);
passwordData = getPasswordDataResult.getPasswordData();
}
// Decrypt the password
Cipher cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherText = Base64.decode(passwordData);
byte[] plainText = cipher.doFinal(cipherText);
String password = new String(plainText, Charset.forName("ASCII"));
return password;
}
}
ObDisclosure: I originally answered this on a blog posting at http://www.frontiertown.co.uk/2012/03/java-administrator-password-windows-ec2-instance/
You can create an instance, set the password and then turn it back into an image. Effectively setting a default password for each instance you create. Wouldn't this be simpler?
Looks like you are looking for the following parts of the API: GetPasswordDataRequest and GetPasswordDataResult
You can also create a Image with default user name and Password setup on that Image.And then launch all instances with that image id..so that you dont need to create and retrieve password evry time..just launch your instance rdp that launched instance with definde credntials in Image. I am doing same.And its perfectly working for me.
I'm trying to digitally sign an XML document using Java. I've got an implementation working with some references I've found that use various implementations in the javax.xml.crypto.dsig package.
However, my current implementation is like many of the examples I've looked at - it's rather verbose and involves using no less than 23 different API classes from the java.xml.crypto.dsig, javax.xml.transform, and java.security packages, among others. It feels like I've entered factory factory factory land, and it took me several hours just to figure out what was going on.
My question is, is there an easier way to do this? If I've got public/private key files and I want to add a <Signature/> to an XML document, is there a library out there that just lets me call something like:
OutputStream signFile(InputStream xmlFile, File privateKey)
...without all of the XMLSignatureFactory/CanonicalizationMethod/DOMSignContext craziness?
I'm not very well-versed in cryptography, and the Java-provided API seems rather daunting for developers like myself trying to become familiar with digital signing. If all of this is necessary or there's currently no friendlier API out there, that's fine and I'm willing to accept that as an answer. I'd just like to know if I'm unnecessarily taking the hard road here.
Have look at Apache XML Security. To use the package to generate and verify a signature, checkout the samples in src_samples/org/apache/xml/security/samples/signature/.
Building from the Apache Santuario CreateSignature example, the shortest thing I could come up with is this. Without the main() and its accompanying output(), it's 20 lines
import java.io.*;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.io.IOUtils;
import org.apache.xml.security.Init;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.signature.XMLSignature;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.utils.Constants;
import org.apache.xml.security.utils.ElementProxy;
import org.w3c.dom.Document;
public class CreateSignature {
private static final String PRIVATE_KEY_ALIAS = "test-alias";
private static final String PRIVATE_KEY_PASS = "test";
private static final String KEY_STORE_PASS = "test";
private static final String KEY_STORE_TYPE = "JKS";
public static void main(String... unused) throws Exception {
final InputStream fileInputStream = new FileInputStream("test.xml");
try {
output(signFile(fileInputStream, new File("keystore.jks")), "signed-test.xml");
}
finally {
IOUtils.closeQuietly(fileInputStream);
}
}
public static ByteArrayOutputStream signFile(InputStream xmlFile, File privateKeyFile) throws Exception {
final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
Init.init();
ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, "");
final KeyStore keyStore = loadKeyStore(privateKeyFile);
final XMLSignature sig = new XMLSignature(doc, null, XMLSignature.ALGO_ID_SIGNATURE_RSA);
final Transforms transforms = new Transforms(doc);
transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
final Key privateKey = keyStore.getKey(PRIVATE_KEY_ALIAS, PRIVATE_KEY_PASS.toCharArray());
final X509Certificate cert = (X509Certificate)keyStore.getCertificate(PRIVATE_KEY_ALIAS);
sig.addKeyInfo(cert);
sig.addKeyInfo(cert.getPublicKey());
sig.sign(privateKey);
doc.getDocumentElement().appendChild(sig.getElement());
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(doc));
return outputStream;
}
private static KeyStore loadKeyStore(File privateKeyFile) throws Exception {
final InputStream fileInputStream = new FileInputStream(privateKeyFile);
try {
final KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
keyStore.load(fileInputStream, KEY_STORE_PASS.toCharArray());
return keyStore;
}
finally {
IOUtils.closeQuietly(fileInputStream);
}
}
private static void output(ByteArrayOutputStream signedOutputStream, String fileName) throws IOException {
final OutputStream fileOutputStream = new FileOutputStream(fileName);
try {
fileOutputStream.write(signedOutputStream.toByteArray());
fileOutputStream.flush();
}
finally {
IOUtils.closeQuietly(fileOutputStream);
}
}
}
I looked at all of the options for signing XML files and decided to go with a non-standard approach. The standards were all way too verbose. Also, I didn't need compatibility with the standards---I just needed signatures on a block of XML.
Probably the easiest way to "sign" a block of XML is to use GPG with a detached signature.