Cannot decrypt encrypted text through BasicTextEncryptor? - java

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.

Related

PGP Encryption - Compile time issue

I am trying to PGP Encrypt a file using Java code. I have generated pgp keys (.asc file) for the same. Below is my Java code:
package extract;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class PGPEncryption {
public static void main(String[] args) throws Exception {
String publicKeyFileName="abc-pub-sub.asc";
String keyUserid="abc";
String input_file_path="test.csv";
String output_file_path="/tmp/output";
camelContext.addRoutes(new RouteBuilder() {
public void configure() throws Exception {
from(input_file_path).marshal()
.pgp(publicKeyFileName, keyUserid).to(output_file_path);
}
});
camelContext.start();
Thread.sleep(5000);
camelContext.stop();
}
}
Below are the Jars I added in my build Path :
bcpg-jdk15on-1.56.jar
bcprov-jdk15on-1.56.jar
camel-core-2.6.0.jar
camel-crypto-2.9.5.jar
commons-logging-1.2.jar
slf4j-api-1.7.25.jar
slf4j-nop-1.7.25.jar
But above code is giving me compile time error as below :
"The method pgp(String, String) is undefined for the type DataFormatClause<ProcessorDefinition<RouteDefinition>>"
Could someone please help me in fixing this ?
Also I tried to export my code as Runnable Jar with compile time errors. But after I execute my Jar file I am facing below error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/fusesource/commons/management/ManagementStrategy
I am not sure if I am missing any basic thing here. Could someone please help here? Thanks in Advance.
Referred Link : PGP Encryption with Apache Camel

Use imported java library

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.

Unable to generate certificate request on android through bouncycastle library

I'm now on developing digital signature app on android.
however, I failed to make a apk file because eclipse show following message
[2013-01-27 20:43:25 - BlowfishCipher] Dx
UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added: Lorg/bouncycastle/mozilla/SignedPublicKeyAndChallenge;
[2013-01-27 20:43:25 - BlowfishCipher] Dx at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123)
[2013-01-27 20:43:25 - BlowfishCipher] Dx at com.android.dx.dex.file.DexFile.add(DexFile.java:163)
I know that the error message indicates that duplicated jar files but I don't know how to
solve it since the duplicated jar (Lorg/bouncycastle/mozilla/SignedPublicKeyAndChallenge;) is the core file of the bouncy caslte library.
and follwing java code shows no syntax error but it cause java.lang.IllegalArgumentException: already added exception
package exam.blowfishcipher;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.security.KeyPair;
import java.security.SecureRandom;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.openssl.PEMWriter;
import android.os.Environment;
import chapter6.PKCS10ExtensionExample;
public class PKCS10Generater
{
public static PKCS10CertificationRequest generateRequest(
KeyPair pair)
throws Exception
{
return new PKCS10CertificationRequest(
"SHA256withRSA",
new X500Principal("CN=Test CA Certificate"),
//new X500Principal("CN=end"),
pair.getPublic(),
null,
pair.getPrivate());
}
public static void pemEncodeToFile(String filename, Object obj, char[] password) throws Exception{
PEMWriter pw = new PEMWriter(new FileWriter(filename));
if (password != null && password.length > 0) {
pw.writeObject(obj, "DESEDE", password, new SecureRandom());
} else {
pw.writeObject(obj);
}
pw.flush();
pw.close();
}
public static void reqGen() throws Exception
{
//create the keys
/*
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
//KeyPairGenerator kpGen = KeyPairGenerator.getInstance()
kpGen.initialize(512, chapter4.Utils.createFixedRandom());
KeyPair pair=kpGen.generateKeyPair();
*/
//PKCS10CertificationRequest request = generateRequest(pair);
KeyPair pair = chapter8.Utils.generateRSAKeyPair();
PKCS10CertificationRequest request = PKCS 10ExtensionExample.generateRequest(pair);
pemEncodeToFile(Environment.getExternalStorageDirectory()+"pkcs10.req", request, null);
PEMWriter pemWrt = new PEMWriter( new OutputStreamWriter(System.out));
pemWrt.writeObject(request);
pemWrt.close();
}
}
Android already includes BouncyCastle in the system, that is why you are getting the error when trying to add it again (on recent versions it is actually in com.android.org.bouncycastle or some such so you shouldn't get the error, in theory). You have to rename the package of BC if you want to include it in your project (with jarjar, etc.). One project that already does this for you is SpongyCastle. Try using that instead of the regular BC jar.
https://github.com/rtyley/spongycastle

EC2 Windows - Get Administrator Password

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.

Is there an easier way to sign an XML document in Java?

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.

Categories

Resources