i have the problam, in existing code encrypt code using php.
this is code for encrypt with php langunage :
<?PHP
$token = "The quick brown fox jumps over the lazy dog.";
$cipher_method = 'aes-256-cbc';
$enc_key = openssl_digest("keyssss", 'SHA256', TRUE);
$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
$crypted_token = openssl_encrypt($token, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
unset($token, $cipher_method, $enc_key, $enc_iv);
?>
but, if i want to decode with java always failed :
this is java code :
#GetMapping("/verify")
public String tokenFB(#RequestParam("accessToken") String accessToken) {
try {
String[] accessTokenSplit = accessToken.split("::");
if (accessTokenSplit.length < 2) {
throw new BadRequestException("accessTokenInvalid");
}
String token = accessTokenSplit[0];
String iv = accessTokenSplit[1];
byte[] tokenByte = Base64.getDecoder().decode(token);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKey secretKey = makeKey();
IvParameterSpec ivParameterSpec = makeIv(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] plainText = cipher.doFinal(tokenByte);
return new String(plainText);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private IvParameterSpec makeIv(String iv) {
byte[] ivHex = DatatypeConverter.parseHexBinary(iv);
return new IvParameterSpec(ivHex);
}
private SecretKey makeKey() {
try {
MessageDigest dg = MessageDigest.getInstance("SHA-256");
byte[] keyByte = dg.digest("secretKeys".getBytes());
return new SecretKeySpec(keyByte, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
the error is Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
how to be decrypt with java languange ?
Solved
Related
Quarkus Native build is throwing exception * Couldn't wrap AES key: No such algorithm: AESWrap*. But working in dev(non-native)
public String encrypt(String data, String keyId, String aesKey) {
try {
byte[] keyBytes = Base64.getDecoder().decode(aesKey);
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, 0, keyBytes.length, "AES");
JWEAlgorithm jweAlgorithm = JWEAlgorithm.A256KW;
EncryptionMethod encryptionMethod = EncryptionMethod.A128GCM;
JWEHeader.Builder headerBuilder = new JWEHeader.Builder(jweAlgorithm, encryptionMethod);
headerBuilder.keyID(keyId);
JWEHeader header = headerBuilder.build();
JWEEncrypter encryptor = new AESEncrypter(secretKey);
encryptor.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance());
JWEObject jweObject = new JWEObject(header, new Payload(data));
jweObject.encrypt(encryptor);
return jweObject.serialize();
} catch (Exception e) {
throw new EncryptionException(e.getMessage());
}
}
Exception:
"threadName":"vert.x-eventloop-thread-2","threadId":27,"mdc":{"x-request-id":"c7e96897-f832-4c6f-a769-3ea8832234cb"},"ndc":"","hostName":"prashant.local","processName":"NativeImageGeneratorRunner$JDK9Plus","processId":37917,"exception":{"refId":1,"exceptionType":"com.nimbusds.jose.JOSEException","message":"Couldn't wrap AES key: No such algorithm: AESWrap","frames":[{"class":"com.nimbusds.jose.crypto.impl.AESKW","method":"wrapCEK","line":80},
{"class":"com.nimbusds.jose.crypto.AESEncrypter","method":"encrypt","line":204},
{"class":"com.nimbusds.jose.JWEObject","method":"encrypt","line":370},
{"class":"com.nimbusds.jose.crypto.impl.AESKW","method":"wrapCEK","line":71},
{"class":"com.nimbusds.jose.crypto.AESEncrypter","method":"encrypt","line":204},
{"class":"com.nimbusds.jose.JWEObject","method":"encrypt","line":370},
Below is the code im using for Decryption.
public String decrypt(String strToBeDecrypted) {
try {
if((strToBeDecrypted.trim().length()!=0) && !(strToBeDecrypted.trim().equals("")) && !(strToBeDecrypted.trim().equalsIgnoreCase("NA"))){
strToBeDecrypted = URLDecoder.decode(strToBeDecrypted, "UTF-8");
DESKeySpec desKeySpec = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey skey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, skey, ivSpec);
byte[] keyByteArray = new BASE64Decoder().decodeBuffer(strToBeDecrypted);
byte[] original = cipher.doFinal(keyByteArray);
return new String(original, "UTF-8");
}
}
catch (Exception e) {
logger.error(ExceptionUtil.getDetailedMessage(e));
}
return "";
}
Im getting "Unknown exception details: name=javax.crypto.BadPaddingException;message=Given final block not properly padded;" at the below line
byte[] original = cipher.doFinal(keyByteArray);
Can anyone pls tell me what is the problem here? Im using the following keys
encryptkey=QvgC9vBXDZyM7RoAxevpHaawEbL5CW8Sp1zjEQ
iterations=19
segments=5
I'm trying to encrypt/decrypt a String in Java. No problem concerning the encryption then stored a in sqlite table. But I always get the same error trying to decrypt it :
"java.security.InvalidKeyException : no IV set when one expected"
Here is my code snippet :
public String encrypt(String password){
try
{
String key = "mysecretpassword";
SecretKeySpec keySpec = null;
keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
return new String(cipher.doFinal(password.getBytes()));
}
catch (Exception e)
{
return null;
}
}
public String decrypt(String password){
try
{
String key = "mysecretpassword";
SecretKeySpec keySpec = null;
keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE,keySpec);
return new String(cipher.doFinal(password.getBytes()));
}
catch (Exception e)
{
System.out.println(e);
return null;
}
}
What am I doing wrong?
You will need to specify an initialization vector in the cipher.init() method:
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
cipher.init(Cipher.DECRYPT_MODE,keySpec, ivSpec);
See: http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/spec/IvParameterSpec.html
The initialization vector should be a random byte array, for a discussion see:
http://en.wikipedia.org/wiki/Initialization_vector
You need an appropriate AES key, try with:
String key = "mysecretpassword";
KeySpec spec = new PBEKeySpec(key.toCharArray(), Salt, 12345678,256);
SecretKey encriptionKey = factory.generateSecret(spec);
Key encriptionKey = new SecretKeySpec(encriptionKey.getEncoded(), "AES");
I have an Python application that creates a few files encrypted with AES/PKCS7. I have to read those files with a Java service. But my code is throwing an exception:
"javax.crypto.IllegalBlockSizeException: last block incomplete in decryption"
Here's my decryption code:
public String Decrypt(String strText)
{
try
{
// Text to decrypt
byte[] test = strText.getBytes();
//bytKey is the same key as Python app
SecretKeySpec objKey = new SecretKeySpec(bytKey, "AES");
Cipher objCipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
objCipher.init(Cipher.DECRYPT_MODE, objKey);
// Here I got an exception >>
byte[] bytValue = objCipher.doFinal(test);
return new String(bytValue);
}
catch (Exception exc)
{
exc.printStackTrace();
}
return "";
}
If I decode the encrypted text before step into doFinal I get another exception:
"javax.crypto.BadPaddingException: pad block corrupted"
public String Decrypt(String strText)
{
try
{
BASE64Decoder decoder = new BASE64Decoder();
byte[] test = decoder.decodeBuffer(strText);
SecretKeySpec objKey = new SecretKeySpec(bytKey, "AES");
Cipher objCipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
objCipher.init(Cipher.DECRYPT_MODE, objKey);
byte[] bytValue = objCipher.doFinal(test);
return new String(bytValue);
}
catch (Exception exc)
{
exc.printStackTrace();
}
return "";
}
I'm not an expert on encrypt/decrypt and I guess it's quite simple to solve.
Any ideas to solve this issue? Thanks in advance!
I am first going to describe the problem which I have, and then give some background to what I am trying to do. Finally I shall paste some relevant code snippets.
I am trying to implement secret key encryption/decryption using the method specified in https://stackoverflow.com/a/992413/171993. If I use that example as-is, it works (although I did notice that I need to re-instantiate the Cipher class, otherwise the decryption produces garbage). However, in my implementation I get the following exception:
java.security.InvalidKeyException: Wrong algorithm: AES or Rijndael required
at com.sun.crypto.provider.AESCrypt.init(AESCrypt.java:77)
at com.sun.crypto.provider.CipherBlockChaining.init(CipherBlockChaining.java:91)
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:469)
at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:217)
at javax.crypto.Cipher.implInit(Cipher.java:790)
at javax.crypto.Cipher.chooseProvider(Cipher.java:848)
at javax.crypto.Cipher.init(Cipher.java:1347)
at javax.crypto.Cipher.init(Cipher.java:1281)
at securitytest.SecurityManager.getCipher(SecurityManager.java:175)
at securitytest.SecurityManager.decryptSecretKey(SecurityManager.java:379)
at securitytest.SecurityManager.<init>(SecurityManager.java:82)
at securitytest.Test.main(Test.java:44)
To beat off the obvious question, yes, I do use the same algorithm: in fact, I assigned AES/CBC/PKCS5Padding to a constant and use that for instantiating both the Cipher class for encryption and decryption. I have also tried using only AES instantiate Cipher for the decryption, but that did not work either.
What I am trying to do is to password-protect a secret key by using AES/CBC/PKCS5Padding. I generate a random salt and initialisation vector. After encrypting the secret key, I append the initialisation vector (an array of bytes) to the encrypted value (also an array of bytes, creating a new array). I then encode this value in Base64 and store it in a Sqlite database, along with the salt (which, for the sake of simplicity, I store as a comma-separated string of values). However when I try to decrypt, I get the above exception. I can verify that directly after my call to the encryption method and directly before the decryption method, the following values are exactly the same (when converted to Base64 so that I can print it out):
The salt
The initialisation vector
The encrypted secret key (i.e. the cipher text)
I have tried both Java 6 and 7: both give the same results. I have also ruled out the unlimited strength jurisdiction policy files as an issue. In fact, I get a similar error if I substitute "AES" with another algorithm and adjust the length of the salt accordingly (for example "Blowfish" with IV length 8, which produces java.security.InvalidKeyException: Wrong algorithm: Blowfish required).
Google has not been able to help me with this problem. If anyone can shed some light on this, I would be very appreciative.
Here are some code snippets (my apologies, it is a little rough):
private static final int INIT_VECTOR_LENGTH = 16;
private static final int PRIVATE_KEY_LENGTH = 128;
private static final int SALT_LENGTH = 16;
private static final int PBE_KEYSPEC_ITERATIONS = 65536;
private static final String CIPHER_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM_MODE = "CBC";
private static final String CIPHER_ALGORITHM_PADDING = "PKCS5Padding";
private static final String DIGEST = "SHA1";
private static final String PLAINTEXT_ENCODING = "UTF8";
private static final String PRNG = DIGEST + "PRNG";
private static final String SECRET_KEY_FACTORY = "PBKDF2WithHmac" + DIGEST;
private static final String CIPHER = CIPHER_ALGORITHM + "/" + CIPHER_ALGORITHM_MODE + "/" + CIPHER_ALGORITHM_PADDING;
private IvParameterSpec ivSpec;
private final BASE64Encoder encoder = new BASE64Encoder();
private final BASE64Decoder decoder = new BASE64Decoder();
private Cipher getCipher(SecretKey key, int mode) {
Cipher cipher = null;
try {
cipher = Cipher.getInstance(CIPHER);
}
catch (NoSuchAlgorithmException e) {System.err.println(System.err.println(e.getMessage());}
catch (NoSuchPaddingException e) {System.err.println(e.getMessage());}
try {
if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(mode, key);
AlgorithmParameters params = cipher.getParameters();
ivSpec = params.getParameterSpec(IvParameterSpec.class);
}
else {
/* This is my point-of-failure. */
cipher.init(mode, key, ivSpec);
}
}
catch (InvalidKeyException e) {System.err.println(e.getMessage());}
catch (InvalidAlgorithmParameterException e) {System.err.println(e.getMessage());}
catch (InvalidParameterSpecException e) {System.err.println(e.getMessage());}
return cipher;
}
private SecurityData.Secrets generateSecrets(SecretKey decryptedKey, byte[] salt, String passphrase) {
/* Generate a new key for encrypting the secret key. */
byte[] raw = null;
PBEKey key = null;
PBEKeySpec password = new PBEKeySpec(passphrase.toCharArray(), salt, PBE_KEYSPEC_ITERATIONS, PRIVATE_KEY_LENGTH);
SecretKeyFactory factory = null;
byte[] initVector = null;
byte[] secretKeyBytes = decryptedKey.getEncoded();
try {
factory = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY);
key = (PBEKey) factory.generateSecret(password);
}
catch (NoSuchAlgorithmException e) {System.err.println(e.getMessage());}
catch (InvalidKeySpecException e) {System.err.println(e.getMessage());}
SecretKeySpec newKey = new SecretKeySpec(key.getEncoded(), CIPHER_ALGORITHM);
/* Encrypt the secret key. */
IvParameterSpec ivSpec = new IvParameterSpec(initVector);
Cipher cipher = getCipher(newKey, ivSpec, Cipher.ENCRYPT_MODE);
try {
raw = cipher.doFinal(secretKeyBytes);
}
catch (IllegalBlockSizeException e) {System.err.println(e.getMessage());}
catch (BadPaddingException e) {System.err.println(e.getMessage());}
return new SecurityData.Secrets(encoder.encode(concatByteArrays(initVector, raw)), joinByteArray(salt));
}
private SecretKey decryptSecretKey(String encryptedKey, String salt, String passphrase) {
/* Get initialisation vector. */
byte[] raw = null, decoded = null, initVector = new byte[INIT_VECTOR_LENGTH];
try {
decoded = decoder.decodeBuffer(encryptedKey);
} catch (IOException e) {System.err.println(e.getMessage());}
System.arraycopy(decoded, 0, initVector, 0, INIT_VECTOR_LENGTH);
raw = new byte[decoded.length-INIT_VECTOR_LENGTH];
System.arraycopy(decoded, INIT_VECTOR_LENGTH, raw, 0, decoded.length-INIT_VECTOR_LENGTH);
IvParameterSpec ivSpec = new IvParameterSpec(initVector);
/* Generate the key. */
byte[] rawSalt = splitByteArrayString(salt);
PBEKeySpec password = new PBEKeySpec(passphrase.toCharArray(), rawSalt, PBE_KEYSPEC_ITERATIONS, PRIVATE_KEY_LENGTH);
SecretKeyFactory factory = null;
PBEKey key = null;
try {
factory = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY);
key = (PBEKey) factory.generateSecret(password);
}
catch (NoSuchAlgorithmException e) {System.err.println(e.getMessage());}
catch (InvalidKeySpecException e) {System.err.println(e.getMessage());}
Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
/* Decrypt the message. */
byte[] stringBytes = null;
try {
stringBytes = cipher.doFinal(raw);
}
catch (IllegalBlockSizeException e) {System.err.println(e.getMessage());}
catch (BadPaddingException e) {System.err.println(e.getMessage());}
/* Converts the decoded message to a String. */
String clear = null;
try {
clear = new String(stringBytes, PLAINTEXT_ENCODING);
}
catch (UnsupportedEncodingException e) {System.err.println(e.getMessage());}
return new SecretKeySpec(clear.getBytes(), CIPHER_ALGORITHM);
}
The SecretKey object needs to return "AES" from its getAlgorithm() method. That's why the example has these steps:
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");