how to implement encrpytion and decryption on a string - java

i want to encrypt a string to make data that is being stored secure, how would i do this. the code is found below. i am new to programming and encryption therefore need help on how to actually encrypt data that is being saved if anyone can guide please?
public class Utilities {
public static final String FILE_EXTENSION = ".bin";
public static boolean saveNote(Context context, Notes notes){
String fileName = String.valueOf(notes.getDateTime()) + FILE_EXTENSION;
not sure if the code provided is sufficient enough to see how to add encryption to a string which is "filename". how would i be able to implement encrypt/decrypt on that?

for simple encryption you can use base64 encoding and decoding. but if you want to high level security you can go with encryption and decryption algorithm like RC4, RC6, RSA, ECC, or AES and many more. for this you can use following java libraries :-
java.security
javax.crypto

Related

Is there any way to get the plain text from signed data using private key?

The plain text is signed using java.security.Signature. Below is the code used to sign the plain text
public String getSignature(String plainText) throws Exception
{
KeyStore keyStore = loadKeyStore(); // A local method to read the keystore file from file system.
PrivateKey privateKey = (PrivateKey) keyStore.getKey(KEY_ALIAS_IN_KEYSTORE, KEYSTORE_PASSWORD.toCharArray());
Signature privateSignature = Signature.getInstance(SIGNATUREALGO);
privateSignature.initSign(privateKey);
privateSignature.update(plainText.getBytes("UTF-8"));
byte[] signature = privateSignature.sign();
return String.valueOf(signature);
// KEY_ALIAS_IN_KEYSTORE, KEYSTORE_PASSWORD and SIGNATUREALGO are all constant Strings
}
Note 1: I found online a way to verify the signature using the public key Java Code Examples for java.security.Signature#verify(). But this is not what I require.
Note 2: I also found a ways to encrypt and decrypt as mentioned here RSA Signing and Encryption in Java. But the use case I have in hand is to get the original plain text from a signed data. Is that possible?
No, you can't retrieve the original content from just the signature.
The signature alone does not contain enough information to restore the original clear text, no matter what keys you have access to.
The basic idea of a signature is to send it together with the clear text. That means the clear text will be visible, but the signature can be used to verify that the message was written (or at least signed) by who claims to have done so and has not been tampered with since then.
Signing something is different from encrypting it. The two often uses the same or related technologies and both fall under cryptography.

Encypting with php openssl and decrypting with Java

I am trying to encrypt a string with php open_ssl and then decrypt it with Java. I thought I kind of understood what was going on, but apparently not.
At first I was unable to get the algorithms to match up. From what I can gather, openssl_private_encrypt() is using RSA and although the documentation is about PKCS1_PADDING, from what I read it seems that it was changed to use PKCS5/7 to become more secure. And I cannot get any Java cipher with RSA/NONE/PKCS5 or PKCS7.
But I thought I was having success by using NoPadding, and filling the block myself. This is with an existing 512 bit key that I converted from DER to PEM with openssl. I had a test string of
0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
I was able to read in the private key in php and encrypt the text with
$fp=fopen("/folder/private_key.pem","r");
$privkey_res=fread($fp,1024);
$privkey = openssl_pkey_get_private($privkey_res);
$padding = OPENSSL_NO_PADDING;
openssl_private_encrypt($texttocrypt, $encryptedtext, $privkey, $padding);
file_put_contents("/folder/encrypted.txt", $encryptedtext );
Then back in Java I then was able to correctly decrypt that string using
Cipher cipherb = Cipher.getInstance("RSA/NONE/NoPadding");
cipherb.init(Cipher.DECRYPT_MODE, publicKey);
decrypted = cipherb.doFinal(text.getBytes());
So I thought I could get things working to be useful. However, then I changed the test string slightly, like the last 'f' to 'g'
0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeg
And then I got complete garbage on the decryption. Although no error. And if I just changed the first character, it still decrypted correctly.
At this point I am not even sure what it is that I don't understand. But is there a way to do my original goal? Encrypt with php open_ssl and decrypt with Java.
Thanks

PGP signature format reader

In my project I need to verify PGP clear signed signatures using a corresponding public key. While I did manage to find a code which does that (For example: https://github.com/cjmalloy/openbitpub/blob/64485d64a699eb6096f01b27d5f7e51dd726602f/src/main/java/com/cjmalloy/obp/server/pgp/PgpUtil.java), it operates on a low level and looks pretty horrible.
I was thinking, perhaps there exist some specialized parsers that can consume -----BEGIN PGP PUBLIC KEY BLOCK-----xxx-----END PGP PUBLIC KEY BLOCK----- and -----BEGIN PGP SIGNED MESSAGE-----xxx-----BEGIN PGP SIGNATURE-----xxx-----END PGP SIGNATURE----- blocks so I can check signatures in a more declarative way?
I've found related PEMReader class from bouncycastle.openssl package but nothing PGP-related so far.
I was thinking, perhaps there exist some specialized parsers that can consume -----BEGIN PGP PUBLIC KEY BLOCK-----xxx-----END PGP PUBLIC KEY BLOCK----- and -----BEGIN PGP SIGNED MESSAGE-----xxx-----BEGIN PGP SIGNATURE-----xxx-----END PGP SIGNATURE----- blocks so I can check signatures in a more declarative way?
A parser will not be enough at all -- you will need to implement lots of OpenPGP-specific functions like symmetric key derivation from strings (for encrypted keys), handling of different types of assymetric cryptography algorithms, hash sums, different kinds of packet nesting, ... -- at least you're not required to implement the OpenPGP CBC mode deriate as you don't require encryption (only signatures).
OpenPGP is much to complicated to write your own parser and crypto code, rely on existing libraries instead. In the end, with Java you've got two possible roads to follow:
Using GnuPG through GPGME's Java interface, which requires a local GnuPG installation.
Using Bouncy Castle for Java which has a pretty much complete OpenPGP implementation in native Java code, but will require you to perform all the crypto operations in Java. The documentation pretty much consists of the JavaDoc for the OpenPGP package.
I've found related PEMReader class from bouncycastle.openssl package but nothing PGP-related so far.
You probably looked in the wrong BouncyCastle package. OpenPGP does not use keys in PEM format (which belongs to the X.509 standard), so this class will not be useful at all.
I came through the same situation sometimes back.
This was resolved by using the bouncy castle dependency and by using the method
decryptAndVerify(InputStream in, OutputStream fOut, InputStream publicKeyIn, InputStream keyIn, char[] passwd)
in PGP util class
The commercial OpenPGP Library for Java offers a convenient API for verifying clear text signatures. Sample code is:
import com.didisoft.pgp.*;
public class VerifyFile {
public static void main(String[] args) throws Exception{
// create an instance of the library
PGPLib pgp = new PGPLib();
// verify and extract the signed content
SignatureCheckResult signatureCheck = pgp.verifyAndExtract("signed.pgp", "sender_public_key.asc", "OUTPUT.txt");
if (signatureCheck == SignatureCheckResult.SignatureVerified) {
System.out.println("The signature is valid.");
} else if (signatureCheck == SignatureCheckResult.SignatureBroken) {
System.out.println("Message corrupted or signature forged");
} else if (signatureCheck == SignatureCheckResult.PublicKeyNotMatching) {
System.out.println("Signature not matching provided public key (the message is from another sender)");
} else {
System.out.println("No signature found in message");
}
}
}
Disclaimer: I work for DidiSoft.

Translating Java RSA encryption routine to Objective-C

I am trying to duplicate an encryption process that is working in Java over to iOS/OSX.
My Java code is as follows:
PublicKey publicKey = KeyFactory.getInstance("RSA").
generatePublic(new RSAPublicKeySpec(firstKeyInteger, secondKeyInteger));
// This always results in the public key OpenSSLRSAPublicKey{modulus=2b3b11f044.....58df890,publicExponent=10001}
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA1ANDMGF1PADDING");
String stringToEncode = "EncodeThisString";
byte[] bytesToEncode = stringToEncode.getBytes("UTF-8");
cipher.init(cipher.PUBLIC_KEY, publicKey);
byte[] encrypted = cipher.doFinal(plain);
The first challenge i'm struggling with is how to use the public key in iOS. Can I just dump the modulus into NSData and use it? Or must I store it in the keychain first? (I don't really need to use the keychain unless I must). Or is there a method similar to generatePublic() were I can recreate the public key using the 2 integers?
Then would I use SecKeyEncrypt to encrypt? Whenever I add this to my project I get Implicit declaration warnings even though I import the Security framework.
Thanks
EDIT -----
I think I have managed to get a Base64 encoded public key, which I believe is what is in a PEM certificate. Now, how to use it.

Java cryptography object in file password

i try to find the good way for the best technology/method for hidden password in a file, but without use external jar or library.
Actually i use one object that represent a list of user name and password. Convert my list in a xml (only in memory) and after that, i store in a file with AES.
Use only java 7, no external library.
Is a good/secure method?
If this operation is no good, is possible to create dynamically xml encrypted?
thanks
You can use a FileOutputStream wrapped in a CipherOutputStream.
It's not really secure to save passwords encrypted with AES because:
1) Where do you store the key? If you store it in the server, if an attacker violates the server and finds the key, he will have complete acces to the users information.
2) Do you really need to know the users' passwords? In many application, for security reasons, it's better to keep only the hash of the password. The username can be stored in plaintext and you can also add a salt to the password to enforce it. You can do that with some algorithms offered by Java7 platform. In this way, even if someone enters your server, he can't use users login informations without breaking the hash function.
Here's an example that worked for me:
public byte[] getHash(String password, byte[] salt, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest digest = MessageDigest.getInstance(algorithm);//The String rapresents the alg you want to use: for example "SHA-1" or "SHA-256"
digest.reset();
digest.update(salt);
return digest.digest(password.getBytes("UTF-8"));
}
You can also look at this link for a more complete example: https://www.owasp.org/index.php/Hashing_Java

Categories