I am not getting any output from this code I passed encrypted text to decrypt ,but the output is unknown, I am not able to find what is wrong with code please help code is posted below
private void findMeaning(HttpServletResponse resp,String encryptText) throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
UnsupportedEncodingException,
IllegalBlockSizeException,
BadPaddingException,
IOException, ShortBufferException, NoSuchProviderException{
String text = encryptText;
String secretKey="ezeon8547";
KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
//Decryption process; same key will be used for decr
dcipher=Cipher.getInstance(key.getAlgorithm());
dcipher.init(Cipher.DECRYPT_MODE, key,paramSpec);
byte[] enc = new sun.misc.BASE64Decoder().decodeBuffer(text);//possible problem here please resolve
byte[] utf8 = dcipher.doFinal(enc);
String charSet="UTF-8";
String plainStr = new String(utf8, charSet);
sendResponse(resp, "Pincode city:" +plainStr);
}}
i have checked and find when i stop running this code byte[] enc = new sun.misc.BASE64Decoder().decodeBuffer(text); then response sent properly,but when this code is participating in a programme the program stop giving output please help about this line of code i am sure problem is with above code
Related
I have this java code for encryption and decryption, which I want to change/convert to Ruby code. I looked up in OpenSSL gem but dint find the "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" combination available for ruby. How do I implement it?
public class EncryptDecryptService {
public String encryptRequestObject(RequestObject requestObject) throws UnsupportedEncodingException, FileNotFoundException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
PublicKey publicKey = getPublicKey(requestObject.getKeyFilename());
byte[] message = requestObject.getString().getBytes("UTF-8");
byte[] secret = encrypt(publicKey, message);
return Base64.encodeBase64String(secret);
}
public String decryptRequestObject(RequestObject requestObject) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
PrivateKey privateKey = getPrivateKey(requestObject.getKeyFilename(), requestObject.getKeyPassword());
byte[] cipherText = Base64.decodeBase64(requestObject.getString());
byte[] decrypted = decrypt(privateKey, cipherText);
return new String(decrypted, "UTF-8");
}
private PublicKey getPublicKey(String filename) throws FileNotFoundException, CertificateException {
FileInputStream fin = new FileInputStream(filename);
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) factory.generateCertificate(fin);
PublicKey publicKey = certificate.getPublicKey();
return publicKey;
}
private PrivateKey getPrivateKey(String filename, String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
FileInputStream fin = new FileInputStream(filename);
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(fin, password.toCharArray());
String str = ks.aliases().nextElement();
PrivateKey privateKey = (PrivateKey) ks.getKey(str, password.toCharArray());
return privateKey;
}
private byte[] encrypt(PublicKey key, byte[] plainText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plainText);
}
private byte[] decrypt(PrivateKey key, byte[] cipherText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(cipherText);
}
}
OAEP uses several parameters, including two digests, one for OAEP (i.e. for hashing the OAEP label) and one for the mask generation function (MGF1), see RFC8017, sec. 7.1.
The identifier RSA/ECB/OAEPWithSHA-256AndMGF1Padding is ambiguous and depends on the provider. For example the SunJCE provider uses SHA-256 as OAEP digest and SHA-1 as MGF1 digest, the BouncyCastle provider uses SHA-256 for both digests.
The following is an example of the encryption with the Java code and the decryption with the Ruby code (the opposite direction is analog).
On the Java side the SunJCE provider is used WLOG and the digests involved are determined:
String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNvs/qUMjkfq2E9o0qn03+KJE7" +
"ASczEbn6q+kkthNBdmTsskikWsykpDPnLWhAVkmjz4alQyqw+mHYP9xhx8qUC4A3" +
"tXY0ObxANUUKhUvR7zNj4vk4t8F2nP3erWvaG8J+sN3Ubr40ZYIYLS6UHYRFrqRD" +
"CDhUtyjwERlz8KhLyQIDAQAB";
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(pubKey));
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
byte[] plaintext = "The quick brown fox jumps over the lazy dog".getBytes(StandardCharsets.UTF_8);
byte[] ciphertext = encrypt(publicKey, plaintext);
System.out.println("Ciphertext: " + Base64.getEncoder().encodeToString(ciphertext));
with
private static byte[] encrypt(PublicKey key, byte[] plainText) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
OAEPParameterSpec oaepParameterSpec = cipher.getParameters().getParameterSpec(OAEPParameterSpec.class);
MGF1ParameterSpec mgf1ParameterSpec = (MGF1ParameterSpec)oaepParameterSpec.getMGFParameters();
System.out.println("Provider : " + cipher.getProvider().getName());
System.out.println("OAEP-Hash : " + oaepParameterSpec.getDigestAlgorithm());
System.out.println("MGF1-Hash : " + mgf1ParameterSpec.getDigestAlgorithm());
return cipher.doFinal(plainText);
}
which corresponds to the posted encrypt() method (except for the additional output). The code produces (e.g.) the following output:
Provider : SunJCE
OAEP-Hash : SHA-256
MGF1-Hash : SHA-1
Ciphertext: WlozD9ojNRQafip41dpuuhBMe7ruH2FBWnMhbAaSuAtPDpHOUyKaAm6mO15BbvL3eTXyqfEQx29dYPJEbUr5T/WXs846PQN6g7Yv25EXGVbPCzc4aIbms76C1jP92wXNEGWMnu624Fq5W9MVXX75mfaY0Fjvrh5k/TFuO4AIxMk=
For completeness it should be mentioned that an explicit specification of the parameters is also possible with:
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");
OAEPParameterSpec oaepParameterSpec = new OAEPParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-1"), PSource.PSpecified.DEFAULT);
cipher.init(Cipher.ENCRYPT_MODE, key, oaepParameterSpec);
whereby this explicit specification is the more robust alternative because of the ambivalence described above.
After the digests have been determined (either because the provider is known or explicitly with the above output) a Ruby implementation can be made.
A possible OAEP implementation for Ruby is openssl-oaep.
With this, the Ruby code for decryption can be implemented as follows:
require 'openssl'
require 'openssl/oaep'
require 'base64'
private_key =
'-----BEGIN PRIVATE KEY-----
MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAM2+z+pQyOR+rYT2
jSqfTf4okTsBJzMRufqr6SS2E0F2ZOyySKRazKSkM+ctaEBWSaPPhqVDKrD6Ydg/
3GHHypQLgDe1djQ5vEA1RQqFS9HvM2Pi+Ti3wXac/d6ta9obwn6w3dRuvjRlghgt
LpQdhEWupEMIOFS3KPARGXPwqEvJAgMBAAECgYADxGqqL7B9/pPOy3TqQuB6tuNx
4SOGm9x76onqUisoF7LhYqJR4Be/LAKHSR2PkATpKvOcMw6lDvCbtQ+j+rSK2PkN
4iDi1RYqbLUbZBS8vhrgU0CPlmgSSp1NBsqMK9265CaJox3frxmBK1yuf22RboIK
pqOzcluuA4aqLegmwQJBAP0+gM/tePzx+53DrxpYQvlfi9UJo7KeqIFL8TjMziKt
EaRGeOZ6UX/r6CQHojYKnNti7pjAwonsdwCTcv1yy7sCQQDP+/ww49VFHErON/MO
w5iYCsrM5Lx+Yc2JAjetCDpkMrRT92cgQ0nxR5+jNeh+gE2AmB9iKlNxsHJoRaPQ
lBRLAkEAl9hiZEp/wStXM8GhvKovfldMAPFGtlNrthtTCDvFXgVoDpgy5f9x3sIU
74WkPcMfSmyHpA/wlcKzmCTRTicHAQJBALUjq7MQ2tAEIgqUo/W52I6i55mnpZsU
pyOqcL8cqW5W0sNGd+SbdizTym8lJkX2jIlw8/RVFLOxjxLNhCzGqx0CQQDeUMnw
7KGP3F7BnbsXCp64YDdihzSO5X/Mfwxw6+S/pyKZ0/X4uwt24kZuoDnFzGWJYlea
sDQC6enIru+ne5es
-----END PRIVATE KEY-----'
key = OpenSSL::PKey::RSA.new(private_key)
label = ''
md_oaep = OpenSSL::Digest::SHA256
md_mgf1 = OpenSSL::Digest::SHA1
cipher_text_B64 = 'WlozD9ojNRQafip41dpuuhBMe7ruH2FBWnMhbAaSuAtPDpHOUyKaAm6mO15BbvL3eTXyqfEQx29dYPJEbUr5T/WXs846PQN6g7Yv25EXGVbPCzc4aIbms76C1jP92wXNEGWMnu624Fq5W9MVXX75mfaY0Fjvrh5k/TFuO4AIxMk='
cipher_text = Base64.decode64(cipher_text_B64)
plain_text = key.private_decrypt_oaep(cipher_text, label, md_oaep, md_mgf1)
print(plain_text) # The quick brown fox jumps over the lazy dog
with the original plaintext as output.
We're migrating an old middleware written in java to our server and we want to write it down in nodejs, and we have no clue how to translate some of the functions:
With the first function we would need to find a solution in nodejs for the Cipher class, which we haven't found yet, is there any "simmetric" or similar package that we can use in node?
public static String encryptBlowFish(String cleartext, String key)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
{
String encBlowFish = "";
SecretKeySpec skeySpec = getGenerateKey(key);
Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
cipher.init(1, skeySpec);
byte[] raw = cipher.doFinal(cleartext.getBytes("UTF8"));
encBlowFish = new Base64Encoder().encode(raw);
encBlowFish = URLEncoder.encode(encBlowFish, "UTF8");
encBlowFish = specialChars(encBlowFish);
return encBlowFish;
}
For the second method it is pretty much the same, we need a solution in node to emulate this behaviour:
private static SecretKeySpec getGenerateKey(String key)
throws NoSuchAlgorithmException
{
SecretKeySpec skeySpec = null;
Provider sunJce = new SunJCE();
Security.addProvider(sunJce);
KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
kgen.init(448);
byte[] raw = key.getBytes();
skeySpec = new SecretKeySpec(raw, "Blowfish");
return skeySpec;
}
Since we've been surfing around and haven't found anything relevant appart from the package "crypto" for node, which looks nice but we don't know which methods to use to emulate the expected result.
If there is anything else I can do to help you understand our issue, please let me know.
Thanks for your time.
I am trying to implement AES/GCM/NoPadding encryption and decryption in JAVA .. the key used is a shared key from the public key of the receiver and the private key of the sender (ECDH).. encryption works well (with and without iv). However, I am unable to decrypt...
I get the exception: javax.crypto.BadPaddingException: mac check in GCM failed
public static String encryptString(SecretKey key, String plainText) throws NoSuchProviderException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
//IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");//AES/ECB/PKCS5Padding //"AES/GCM/NoPadding", "BC"
byte[] plainTextBytes = plainText.getBytes("UTF-8");
byte[] cipherText;
//cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
cipher.init(Cipher.ENCRYPT_MODE, key);
return new String(Base64.getEncoder().encode(cipher.doFinal(plainTextBytes)));
}
public static String decryptString(SecretKey key, String
cipherText) throws NoSuchProviderException,
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException,
UnsupportedEncodingException, ShortBufferException {
Key decryptionKey = new SecretKeySpec(key.getEncoded(),
key.getAlgorithm());
IvParameterSpec ivSpec = new IvParameterSpec(ivString.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");//AES/GCM/NoPadding", "BC");
cipher.init(Cipher.DECRYPT_MODE, decryptionKey, ivSpec);
return new String (Base64.getEncoder().encode(cipher.doFinal(Base64.getDecoder().decode(cipherText.getBytes()))));
}
You must use exactly the same IV for encryption and decryption of the same ciphertext and it must be different for each encryption that produces different ciphertexts. The IV is not secret, so you can send it along with the ciphertext. Usually, it is simply prepended to the ciphertext and sliced off before decryption.
You need to supply an instance of GCMParameterSpec (which includes the IV) for both of the Cipher.init calls. As has already been pointed out, the IV has to be the same for both encryption and decryption, and must be unique.
I'm searching a known encryption algorithm that would let me encrypt data with a key and if the data is decrypted with another key would give me data that is different from the first one. It's string data. I tried AES but the problem is that the result of decryption using a wrong key gives a lot of invalid symbols so the resulting String is differentiable from a result given with a good key.
Is there a work around to this?
I did this so far:
private static final String truc = "f41a3ff27aab7d5c";
public static String encryptPass(String pass,String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(key.getBytes("UTF-8"));
byte[] digest = md.digest();
BCrypt bcrypt = new BCrypt();
SecretKey keyL = new SecretKeySpec(digest, "AES");
Cipher AesCipher = Cipher.getInstance("AES/CTR/NoPadding");
AesCipher.init(Cipher.ENCRYPT_MODE, keyL, new IvParameterSpec(truc.getBytes()));
byte[] encVal = AesCipher.doFinal(pass.getBytes());
pass = Base64.encodeToString(encVal, Base64.DEFAULT);
Log.i("ADA", "encoded pass: " + pass);
return pass;
}
public static String decryptPass(String encPass , String key) throws NoSuchAlgorithmException, UnsupportedEncodingException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(key.getBytes("UTF-8"));
byte[] digest = md.digest();
SecretKey keyL = new SecretKeySpec(digest, "AES");
Cipher AesCipher = Cipher.getInstance("AES/CTR/NoPadding");
AesCipher.init(Cipher.DECRYPT_MODE, keyL, new IvParameterSpec(truc.getBytes()));
byte[] decodedValue = Base64.decode(encPass, Base64.DEFAULT);
byte[] decValue = AesCipher.doFinal(decodedValue);
String decryptedValue = new String(decValue);
Log.i("ADA", "decrpyted pass: " + decryptedValue);
return decryptedValue;
}
After reading the answer of MaybeWeCouldStartAVar, last paragraph I used "AES/CTR/NoPadding".
When I'm saying a well formed String I'm expecting mostly ASCII chars 32 to 125.
Is there something out there that would respond to my needs, or should I just roll my own encryption algorithm (I heard it's not advised but if it's my only option well..)?
I'm not trying to restrict access to any data. Data is fully visible by anyone who would use the app but unless they have the right key they should see erroneous data (that don't obviously look erroneous).
The idea is to restrain brute force.
I have a problem when encrypting that causes the error:
javax.crypto.IllegalBlockSizeException: data not block size aligned
at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(Cipher.java:2086)
at com.lcp.sso.logic.SsoCipher.encode(SsoCipher.java:89)
The constructor for the object:
public MyCipher() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException {
Security.addProvider(new BouncyCastleProvider());
KeyGenerator keyGen = KeyGenerator.getInstance("DESede", "BC");
keyGen.init(new SecureRandom());
SecretKey keySpec = keyGen.generateKey();
this.sharedKey = keySpec.getEncoded().toString();
this.encrypter = Cipher.getInstance("DESede/ECB/Nopadding", "BC");
this.encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
this.decrypter = Cipher.getInstance("DESede/ECB/Nopadding", "BC");
this.decrypter.init(Cipher.DECRYPT_MODE, keySpec);
}
The method in which the error occurs:
public String encode(String arg_text) throws IllegalBlockSizeException, BadPaddingException {
byte[] encrypt = arg_text.getBytes();
if(encrypt.length % 8 != 0){ //not a multiple of 8
//create a new array with a size which is a multiple of 8
byte[] padded = new byte[encrypt.length + 8 - (encrypt.length % 8)];
//copy the old array into it
System.arraycopy(encrypt, 0, padded, 0, encrypt.length);
encrypt = padded;
}
byte[] b = Base64.encodeBase64URLSafe(encrypt);
return Base64.encodeBase64String(encrypter.doFinal(b));
}
The error happens when calling that last method there. I'd swear that I'm making it the right block size, there, by null-padding the byte array to make sure it's a multiple of 8. I just don't know what went wrong!
I'm using:
Eclipse Version: Juno Service Release 1
Server: Tomcat v7.0 Server at Localhost ( specifically 7.0.32 )
--- EDIT ---
Program isn't working yet, (EDIT: YES IT IS! Muahahahaha!) but this problem is solved.
The constructor for the object:
public MyCipher() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, InvalidParameterSpecException, InvalidAlgorithmParameterException {
Security.addProvider(new BouncyCastleProvider());
KeyGenerator keyGen = KeyGenerator.getInstance("DES", "BC");
keyGen.init(new SecureRandom());
SecretKey keySpec = keyGen.generateKey();
this.sharedKey = new String( Base64.encodeBase64URLSafe( keySpec.getEncoded() ) );
this.encrypter = Cipher.getInstance("DES/CBC/PKCS5Padding", "BC");
this.encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
AlgorithmParameters params = this.encrypter.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
IvParameterSpec ivSpec = new IvParameterSpec(iv);
this.sharedIV = new String( Base64.encodeBase64URLSafe( iv ) );
this.decrypter = Cipher.getInstance("DES/CBC/PKCS5Padding", "BC");
this.decrypter.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
}
And the encrypting method is:
public String encode(String arg_text) throws IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] encrypt = arg_text.getBytes();
return new String( Base64.encodeBase64URLSafe(encrypter.doFinal(encrypt)), "US-ASCII");
}
It's now working to encrypt and decrypt just fine. Thank you VERY much.
Strange code in some aspects. Begining by why your code doesn't work, you are making sure that the size of encrypt is a multiple of 8, but you are trying to cipher byte[] b = Base64.encodeBase64URLSafe(encrypt); which may not be a multiple of 8. The following code should work:
public String encode(String arg_text) throws IllegalBlockSizeException, BadPaddingException {
byte[] encrypt = arg_text.getBytes();
if(encrypt.length % 8 != 0){ //not a multiple of 8
//create a new array with a size which is a multiple of 8
byte[] padded = new byte[encrypt.length + 8 - (encrypt.length % 8)];
//copy the old array into it
System.arraycopy(encrypt, 0, padded, 0, encrypt.length);
encrypt = padded;
}
return new String(Base64.encodeBase64URLSafe(encrypter.doFinal(b)), "US-ASCII");
}
Now, where there is this.encrypter = Cipher.getInstance("DESede/ECB/Nopadding", "BC"); do you notice the "Nopadding" part of the string? Well, the code does what you ask it to do... but the library can do the padding work for you, you just have to tell it. Try this.encrypter = Cipher.getInstance("DESede/ECB/PKCS5Padding", "BC"); instead and see if it works.
But really, why would you want to use 3DES in ECB mode? Unless the reason is legacy (which is unlikely from what I see here), it makes no sense. I believe you need to read a bit more about cryptography.