Couldn't wrap AES key: No such algorithm: AESWrap(quarkus native) - java

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},

Related

encrypt with php and failed decrypt aes-256-cbc with java

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

How to fix "java.security.InvalidKeyException: Unsupported key algorithm: EC. Only RSA supported" while using Keystore in api 18

I need to store sensitive data in local storage with an API 18 , i choose to use the Keystore. I try several solution but none worked.
I try to make my RSAPrivateKey in PrivateKey without cast but it don't work.
I also try to use other crypting algorithm but i never success to make them work in API 18
public String decryptString(String alias, String encryptedText) {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
String decryptedText = "";
try {
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);
RSAPrivateKey privateKey = (RSAPrivateKey) privateKeyEntry.getPrivateKey();
Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding");
output.init(Cipher.DECRYPT_MODE, privateKey);
CipherInputStream cipherInputStream = new CipherInputStream(
new ByteArrayInputStream(Base64.decode(encryptedText, Base64.DEFAULT)), output);
ArrayList<Byte> values = new ArrayList<>();
int nextByte;
while ((nextByte = cipherInputStream.read()) != -1) {
values.add((byte)nextByte);
}
byte[] bytes = new byte[values.size()];
for(int i = 0; i < bytes.length; i++) {
bytes[i] = values.get(i).byteValue();
}
decryptedText = new String(bytes, 0, bytes.length, "UTF-8");
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
return decryptedText;
}
public String encryptString(String alias, String initialText) {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
String encryptedText = "";
try {
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);
PublicKey publicKey = privateKeyEntry.getCertificate().getPublicKey();
// Encrypt the text
if(initialText.isEmpty()) {
Log.e(TAG, "initialText is Empty");
return "";
}
Cipher input = Cipher.getInstance("RSA/ECB/PKCS1Padding");
input.init(Cipher.ENCRYPT_MODE, publicKey);//Need RSA private or public key
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(
outputStream, input);
cipherOutputStream.write(initialText.getBytes("UTF-8"));
cipherOutputStream.close();
byte [] vals = outputStream.toByteArray();
encryptedText = Base64.encodeToString(vals, Base64.DEFAULT);
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
return encryptedText;
}
Here is the erot i get. I would like to success to keep my data in a secure place
java.security.InvalidKeyException: Unsupported key algorithm: EC. Only RSA supported
at com.cryptor.Cryptor.encryptString(Cryptor.java:108)
I don't see where/when you generate your RSA key. On my side, I have done the following steps :
Create/retrieve the Keystore
Generate RSA keys with a KeyPairGenerator (be careful : different methods since Android M)
val generator = KeyPairGenerator.getInstance(ALGORITHM, CryptoConstants.ANDROID_KEY_STORE)
Here, ALGORITHM="RSA" and not "RSA/ECB/PKCS1Padding" and CryptoConstants.ANDROID_KEY_STORE = "AndroidKeyStore" (for example)
Save keys in the Keystore
Encrypt with the public key
Decrypt with the private key
With these steps, my encryption methods are
fun encrypt(publicKey: PublicKey, rawText: ByteArray): String {
try {
val cipher = CipherUtil.getStandardCipherInstance(TRANSFORMATION) // TRANSFORMATION = "RSA/ECB/PKCS1Padding"
cipher.init(Cipher.ENCRYPT_MODE, publicKey)
val bytes = cipher.doFinal(rawText)
return Base64.encodeToString(bytes, BASE64_SETTINGS) // BASE64_SETTINGS = Base64.NO_WRAP
} catch (e: GeneralSecurityException) {
throw SecurityException(e)
}
}
fun decrypt(privateKey: PrivateKey, base64CipherBytes: ByteArray): ByteArray {
try {
val cipher = CipherUtil.getStandardCipherInstance(TRANSFORMATION) // TRANSFORMATION = "RSA/ECB/PKCS1Padding"
cipher.init(Cipher.DECRYPT_MODE, privateKey)
val encryptedData = Base64.decode(base64CipherBytes, BASE64_SETTINGS) // BASE64_SETTINGS
return cipher.doFinal(encryptedData)
} catch (e: GeneralSecurityException) {
throw SecurityException(e)
}
}
Btw, you can bypass the Base64 encoding if you don't need it.

.NET equivalent of Java KeyFactory.getInstance "RSA"/"RSA/ECB/PKCS1Padding"

I have the following code,
public static String encrypt(String plainText, String key){
try{
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.decode(key, Base64.DEFAULT)));
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeToString(cipher.doFinal(plainText.getBytes("UTF-8")),Base64.DEFAULT);
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
I want to convert this to C#. I have tried CryptUtils but it doesn't work https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.Common/CryptUtils.cs
Sample key,
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ9AMIIBCgKCAQEAoqB1N9kugk4UKYnbh0fcg3qYyYKP0m4B
MjWd05ReeAdj+7JRYDEKO6xthDdVSdRO1/2V+YtY8DnXWnxRaICwu8235s3imZCyqgYnomPWdY+F
K540oTz/zug+9wbrlzt/WQFUU4lPlQbzm/Gjw8XfaCozT0e3bnWQcD7rORCOyuJgwSGgREjTv1ss
pgEaKTMknii9vpGZLeAXwoeIYROhuT4IoIkPDhtY0/UZiCi6v7Ja2dmy53VlWIkcm3rcnSJdvpXr
OgiHvaNABHmeymNycNqd6WUaysBRheluQ86nq/2nZPW0gcvmYt5zbMMYX3yY/n2WtAKeNQBAEW1q
b0s6MwIDAQAB
Possible encryped value,
Y3VTjghDnTrCeG8C/RklKsJ3Y0Mt89sSGGin28E4iQPQvKqeZBws7rBQEZaRamDWftxCkEYZs4Qh
V2l4IVlrawdtRmQlcQh8McrpqP/97Gz8pEDEYnqA7kqBTqZw0Z5o0WsshGSwiAQ9wNSym4xHejkq
zrKxWP8XCMkcT0NlKlRMoqKKICFKZbqWeSQkQM5y9OEcmB6inNNkJCoM1Ip48+cK3cOE6dqXNVrl
sSTZ8WQKwoB3dJmcYqexR3kAvBYdX6ZxEF+2+6b9h8+tc5G7Y5R2eqycyUossdkCcI3fNVhyc72P
axCjZFWZUgfDGCxg1WNhStrH9L8c59P35JKKug==
Since i don't have the private key, i can't decrypt, but at least this produces the right lengthed values.
So try this (you need bouncycastle for reading pem):
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
var keyBytes =
Convert.FromBase64String(
"MIIBI...."); // your key here
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
RSAParameters rsaParameters = new RSAParameters();
rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
byte[] plaintext = Encoding.UTF8.GetBytes("amount=1&currency=AED");
byte[] ciphertext = rsa.Encrypt(plaintext, false);
string cipherresult = Convert.ToBase64String(ciphertext);

java Decryption logic: javax.crypto.BadPaddingException

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

Error decrypting in java

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");

Categories