java android URL encrypting - java

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.

Related

Signature.verify is throwing an exception Signature length not correct: got 248 but was expecting 256

java version 1.8
import java.io.ByteArrayInputStream;
import java.security.KeyFactory;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
/**
*
* #author user
*/
public class Test {
public static void main(String[] args) throws Exception {
String publicKeyB64 = "MIIJRzCCBy+gAwIBAgITIAAJCdv4ae0wATxOVgAAAAkJ2zANBgkqhkiG9w0BAQsFADCBizELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEVMBMGA1UECxMMTWljcm9zb2Z0IElUMR4wHAYDVQQDExVNaWNyb3NvZnQgSVQgVExTIENBIDIwHhcNMTkwODE5MDEzMTA2WhcNMjEwODE5MDEzMTA2WjAq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VkYWY0YzItZTdiYS00NDE5LTljYmUtYjQ4NWE2ZTNiNGQ1XCIsXCJ2ZXJzaW9uXCI6XCJFeElkVG9rLlYxXCIsXCJhbXVybFwiOlwiaHR0cHM6Ly9vdXRsb29rLm9mZmljZTM2NS5jb206NDQzL2F1dG9kaXNjb3Zlci9tZXRhZGF0YS9qc29uLzFcIn0iLCJuYmYiOjE1OTMwMjA4MzAsImV4cCI6MTU5MzA0OTYzMCwiaXNzIjoiMDAwMDAwMDItMDAwMC0wZmYxLWNlMDAtMDAwMDAwMDAwMDAwQDhlOTAwMzU4LTliYzAtNGJkMi05ZjM0LTQ1OTk2Nzg5OTA1ZCIsImF1ZCI6Imh0dHBzOi8vbWFpbGFwcC5mb3JjZS5jb20vY2xpZW50cy9tYWlsYXBwL2FjdGl2YXRpb24ifQ";
String signature = "oifeWN-wnci-WCS6XPLC-74ynG9rmXdePVfMMxX9WsAXOK5tvRpNmNsPqu9bllufAIUhgpNIYtHEB39-_o2pzpugyfkohLJfPovEQa-1X8zzudjxY3j5tRyISzVuwL9l6zROhJIdOvXsoarzcuQ38j492H7ol7auTvfDI4Mwu4Ri_e2rbiFYWsYU36Htj39DEiOvpQ12z7Onu-Yrj1inICTDtJsOdv9HWrO2nZ5IwRdl45Tt0Ks3ZrBeStleNVCXQdU_xKvYtbO02fUfgkFrIzEUZYHgXbK8sE2m0phmeU7Wp-KdW4jVVl9yLQtB98_FJJfw9tI4Oys2NBBY2sLyhQ";
RSAPublicKey secret = null;
try {
secret = null;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(new ByteArrayInputStream(Base64.getMimeDecoder().decode(publicKeyB64)));
secret = (RSAPublicKey) cert.getPublicKey();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyFactory kf = KeyFactory.getInstance("RSA");
Signature privateSignature = Signature.getInstance("SHA256withRSA");
privateSignature.initVerify(secret);
privateSignature.update(data.getBytes("UTF-8"));
System.out.println(privateSignature.verify(Base64.getMimeDecoder().decode(signature.getBytes())));
}
}
Getting the following exception:
Exception in thread "main" java.security.SignatureException: Signature length not correct: got 248 but was expecting 256
at sun.security.rsa.RSASignature.engineVerify(RSASignature.java:211)
at java.security.Signature$Delegate.engineVerify(Signature.java:1394)
at java.security.Signature.verify(Signature.java:771)
at com.ciphercloud.plugin.salesforce.rewriters.Test.main(Test.java:35)
One more question:
Earlier, I used the Base64.getDecoder().decode(signature.getBytes())) but it's throwing an error, so I changed to Base64.getMimeDecoder().decode(signature.getBytes())). May I know why it faild with Base64.getDecoder().decode()?
The problem here is the wrong decoding.
Neither Mime (Base64.getMimeDecoder().decode()) nor Base64 (Base64.getDecoder().decode()) are correct.
JWT uses Base64url encoding, not Base64. The difference are the - and _ characters, which are used in base64url to replace the + and / of the Base64 standard. Also the padding = is omitted in Base64url encoding.
The correct way to decode the JWT header, payload and signature is to use the Base64url decoder:
Base64.getUrlDecoder().withoutPadding().decode()

DB connection with encrypted password

For making the database connection in spring 3 i use xml which have defined bean
<bean id="griffDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" p:driverClass="${DRIVER_CLASS}" p:jdbcUrl="${DB_URL}"
p:minPoolSize="${MIN_DB_POOL_SIZE}" p:maxPoolSize="${DB_POOL_SIZE}"
p:maxStatements="${DB_POOL_SIZE}"p:idleConnectionTestPeriod="${IDLE_CONNECTION_TEST_PERIOD}"p:loginTimeout="${LOGIN_TIMEOUT}" scope="singleton"></bean>
here DB_URL value is read from property file
DB_URL:jdbc:mysql://localhost:3306/databaseautoReconnect=true&user=root&password= [B#42e21073
This password in url is encrypted using AES.
The requirement is that i should write a code that when spring go for making the connection to the database it should itself decrypt the password and make the connection.
How can i achieve that?
I have used BASE64Encoder & BASE64Decoder. later You will modify my code to use a secure/better encryption/decryption algorithm.
You first encoded your database password by using the below code:
private String encode(String str) {
BASE64Encoder encoder = new BASE64Encoder();
str = new String(encoder.encodeBuffer(str.getBytes()));
return str;
}
Now You use wrapper class for org.apache.commons.dbcp.BasicDataSource and overridden setPassword() method:
import java.io.IOException;
import org.apache.commons.dbcp.BasicDataSource;
import sun.misc.BASE64Decoder;
public class MyCustomBasicDataSource extends BasicDataSource{
public synchronized void setPassword(String encodedPassword){
this.password = decode(encodedPassword);
}
private String decode(String password) {
BASE64Decoder decoder = new BASE64Decoder();
String decodedPassword = null;
try {
decodedPassword = new String(decoder.decodeBuffer(password));
} catch (IOException e) {
e.printStackTrace();
}
return decodedPassword;
}
}
This way You can decoding(BASE64Decoder) the encoded password .

How to Send blowfish key over Network in java

I have a Java Project to Authenticate images over a wireless network. I am using blowfish for encryption of images. The problem I am facing is how to send the blowfish symmetric key to the receiver so that he can decrypt the image. I am relatively new to cryptography.Please include the code snippet to illustrate the same.
package ClientModule;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
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.swing.*;
public class ImageEncryption_Client
{
KeyGenerator keyGenerator = null;
public static SecretKey secretKey = null;
public static Cipher cipher = null;
ImageEncryption_Client(){
try {
/**
* Create a Blowfish key
*/
keyGenerator = KeyGenerator.getInstance("Blowfish");
secretKey = keyGenerator.generateKey();
System.out.println(secretKey.toString());
/**
* Create an instance of cipher mentioning the name of algorithm
* - Blowfish
*/
cipher = Cipher.getInstance("Blowfish");
System.out.println(cipher.toString());
} catch (NoSuchPaddingException ex) {
System.out.println(ex);
} catch (NoSuchAlgorithmException ex) {
System.out.println(ex);
}
}
private void encrypt(String srcPath, String destPath)
{
File rawFile = new File(srcPath);
File encryptedFile = new File(destPath);
InputStream inStream = null;
OutputStream outStream = null;
try {
/**
* Initialize the cipher for encryption
*/
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
/**
* Initialize input and output streams
*/
inStream = new FileInputStream(rawFile);
outStream = new FileOutputStream(encryptedFile);
byte[] buffer = new byte[1024];
int len;
while ((len = inStream.read(buffer)) > 0) {
outStream.write(cipher.update(buffer, 0, len));
outStream.flush();
}
outStream.write(cipher.doFinal());
inStream.close();
outStream.close();
} catch (IllegalBlockSizeException ex) {
JOptionPane.showMessageDialog(null,"An Exception Occurred","Exception",JOptionPane.ERROR_MESSAGE);
System.out.println(ex);
} catch (BadPaddingException ex) {
JOptionPane.showMessageDialog(null,"An Exception Occurred","Exception",JOptionPane.ERROR_MESSAGE);
System.out.println(ex);
} catch (InvalidKeyException ex) {
JOptionPane.showMessageDialog(null,"An Exception Occurred","Exception",JOptionPane.ERROR_MESSAGE);
System.out.println(ex);
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null,"An Exception Occurred","Exception",JOptionPane.ERROR_MESSAGE);
System.out.println(ex);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null,"An Exception Occurred","Exception",JOptionPane.ERROR_MESSAGE);
System.out.println(ex);
}
}
void enc(String filename)//, String dir)
{
String fileToEncrypt = filename;
String arr[]=filename.split("\\.");
String encryptedFile = arr[0]+"_encrypted."+arr[1];
String directoryPath = "C:\\Users\\Public\\Pictures\\Sample Pictures\\";
encrypt(directoryPath + fileToEncrypt,
directoryPath + encryptedFile);
}
public static void main(String... kkk)
{
new ImageEncryption_Client().enc("Koala.jpg");//,"");
}
}
First off, I wouldn't tread into this area without doing a bit more research or consulting a security expert.
One really good resource on crypto specifically targeted at developers is: https://www.schneier.com/books/cryptography_engineering/
Now on to answering your question. I would first question whether you actually need to do key-exchange or whether you could get away with setting up a pre-shared secret / key pair on both sides.
Key Exchange
Key exchange is the class of problem you're asking about. There are many implementations:
http://en.wikipedia.org/wiki/Key_exchange
Diffie Hellman is a classic approach which is popular in SSL and TLS:
http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
A java implementation example of Diffie Hellman can be found here:
http://docs.oracle.com/javase/7/docs/technotes/guides/security/crypto/CryptoSpec.html#DH2Ex
Pre-shared Key
Key exchange is complex and requires that you own both sides of the communication. Another approach would be to place a shared secret on both ends of the communication. The simplest approach would be to share a symmetric key. http://en.wikipedia.org/wiki/Shared_secret
A slightly more secure approach would be to use asymmetric keys (public key crypto) where each side generates it's own public private key pair and then you pre-share the public key with the other end. So in the classic example where Alice and Bob want to communicate securely, Alice would give Bob her public key and Bob would encrypt all data sent to Alice with her public key. She could then decrypt it with her private key. This approach has the advantage where if any one side is compromised the attacker can't read messages encrypted for the other side. More details are outlined here:
http://en.wikipedia.org/wiki/Public-key_cryptography
A third and slightly more granular approach building on the last one would be to generate a symmetric key per image and encrypt the image with that key. Then encrypt the symmetric key with the public key of the party you're sending the data to. When sending the image over the wire you'd include the encrypted key and the encrypted image. This model is useful because symmetric encryption is faster and better suited for large files like images but combining them in this way you still get the benefits of using public key crypto to protect the transport.
If you happen to be doing this up on AWS, their KMS service would make it very easy to have a shared encryption key across servers. They also use a multi-level crypto approach similar to the last model but in this case the master key is stored on a hardware security module (HSM), which has the added benefit that the master key is never known and can never be pulled off the chip it lives on:
http://aws.amazon.com/kms/

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.

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.

Categories

Resources