I used below code for encryption using AES/ECB/PKCS5Padding algorith, function:
public static void setKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")), Base64.DEFAULT);
} catch (Exception e) {
// System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
Output:
Meeting ID : 20201228165764
Passcode: 769762
Encrypted values:
meetingid: LfD3obeP45AAGXYxPiByvQ==
passcode: fcJSdMArO3vUOL/WxwzRfw==
I used below AESEncryption code in iOS, but get a different encryption key, function:
func AESEncryption(key: String) -> String? {
let keyData: NSData! = (key as NSString).data(using: String.Encoding.utf8.rawValue) as NSData!
let data: NSData! = (self as NSString).data(using: String.Encoding.utf8.rawValue) as NSData!
let cryptData = NSMutableData(length: Int(data.length) + kCCBlockSizeAES128)!
let keyLength = size_t(kCCKeySizeAES128)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(kCCOptionECBMode + kCCOptionPKCS5Padding)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
keyData.bytes, keyLength,
nil,
data.bytes, data.length,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
var bytes = [UInt8](repeating: 0, count: cryptData.length)
cryptData.getBytes(&bytes, length: cryptData.length)
var hexString = ""
for byte in bytes {
hexString += String(format:"%02x", UInt8(byte))
}
return hexString}
return nil //Check condition nil
}
In android code secret key is generated is different than iOS. Can you please help to get same encrypted key from AES/ECB/PKS5padding algorithm? I am checking with https://8gwifi.org/CipherFunctions.jsp link.
In your Swift code, you're just using the string bytes as-is without hashing.
Note that you shouldn't be using SHA-1 for this; you should be using a KDF instead, or (most ideally) a prepackaged library that does all of this error-prone operation for you.
Related
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
I have the following code on Java that decrypts AES encryption and I need to do the same on Node.js
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String decrypt(String strToDecrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
I have tried using Crypt under the following code, but it doesn't give me the same results
var aesDecrypt = (text, password, bit) => {
var decipher = crypto.createDecipheriv('aes-' + bit + '-ecb', password, Buffer.alloc(0));
decipher.setAutoPadding(false);
return Buffer.concat([
decipher.update(text, 'base64'),
decipher.final()
]).toString();
};
How could I mimick that Java code from above into Node.js?
As James says, the Java code is hashing (and truncating) the password to form the key. Also it does use standard padding. The following works for ASCII data:
const crypto = require ('crypto');
const mydecrypt = (pw,ctx) => {
var h = crypto.createHash('sha1'); h.update(pw,'utf8'); var k = h.digest().slice(0,16);
var d = crypto.createDecipheriv('aes-128-ecb', k, Buffer.alloc(0));
return Buffer.concat([d.update(ctx,'base64'), d.final()]) .toString();
}
console.log(mydecrypt('password','ks7qtmk7kt5riV/Qyy3glQ=='));
->
testdata
It may not work for non-ASCII data. Java new String(byte[]) uses a JVM-dependent encoding which may be UTF8 or may be something different depending on your platform, build, and environment, none of which you described. OTOH nodejs Buffer.toString() always uses UTF8. You may need to change it to toString(somethingelse) to match the Java.
If this 'password' is truly a password, i.e. chosen or even remembered by one or more human(s), using a simple hash of it is very weak and will probably be broken if used for anything not utterly trivial; you should use a Password-Based Key Derivation Function designed for the purpose by someone competent, like older (PKCS5) PBKDF2 or newer bcrypt, scrypt, or argon2. However, that's not a programming question and is offtopic here; it has been discussed many times and at length on https://crypto.stackexchange.com and https://security.stackexchange.com .
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.
I have recently used the AES CBC 128 algorithm in Java in order to cipher data. Now I need to rebuild that algorithm in PHP, but I have no idea how, because PHP algorithms on the internet return different results. Maybe you can help me.
This is the Java-code to encrypt:
private SecretKeySpec secretKey;
private IvParameterSpec ivSpec;
public void setKey(String myKey) {
MessageDigest sha = null;
try {
byte[] key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
byte[] iv = new String("1010101010101010").getBytes("UTF-8");
ivSpec = new IvParameterSpec(iv);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public String encrypt(String strToEncrypt) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
return Base64.encode(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String decrypt(String strToDecrypt) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
return new String(cipher.doFinal(Base64.decode(strToDecrypt)));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
AESText aes = new AESText();
final String secretKey = "com.secure.test.projectjasdS/FjkGkGhkGjhG786Vjfg=tjGFGH";
aes.setKey(secretKey);
String originalString = "test set se ts et set s et se";
String encryptedString = aes.encrypt(originalString);
String decryptedString = aes.decrypt(encryptedString);
System.out.println("origin: " + originalString);
System.out.println("encrypted: " + encryptedString);
System.out.println("decrypted: " + decryptedString);
}
This is my php code:
protected $key;
protected $method = 'AES-128-CBC';
protected $iv = '1010101010101010';
protected $option = OPENSSL_CIPHER_AES_128_CBC;
function __construct($key)
{
$this->key = $key;
}
public function encrypt($data) {
if (is_null($data)) {
return "Error " . INVALID_PARAMS_ENCRYPTIONS . ": Data is null ";
}
$enc = openssl_encrypt($data, $this->method, $this->key, $this->option, $this->iv);
return base64_encode($enc);
}
public function decrypt($data) {
if (is_null($data)) {
return "Error " . INVALID_PARAMS_ENCRYPTIONS . ": Data is null ";
}
$data = base64_decode($data);
$dec = openssl_decrypt($data, $this->method, $this->key, $this->option, $this->iv);
return $dec;
}
When I encrypted data from java encryption, This result cannot decrypt on Php decryption.
Can you guys possibly help me with building a PHP script, that returns the same results with java encryption?
At first glance I see three issues here:
First: you are not using the same mode: in java you have AES/ECB/PKCS5Padding whereas your php uses AES-128-CBC.
Second: you probably aren't using the same IV's in the Java and PHP code (IV's are irrelevant for ECB, but once you switch your java to CBC you will need it):
You have $iv = '1010101010101010' (which is then passed to openssl) in your php but nothing like that in your java.
At the very least, you will probably need something like that in your Java part as well:
cipher.init(Cipher.DECRYPT_MODE/ENCRYPT_MODE, secretKey, new IvParameterSpec(iv))
with iv being a byte[] containing your IV bytes.
Third: once the problems above are addressed, padding may be the next breaking thing: your java cipher specification mentions PKCS5Padding. You need to make sure that both of your counterparts use the same.
edit: Fourth: One more issue is the way you derive the key bits to be used. In java you take the first 16 bytes of a sha1-hash, and in php you just pass $key to openssl. openssl might be deriving the encryption key in a different way.
When building cryptography-related tools using block ciphers, it's always nice to revisit classics like Block cipher mode of operation and Padding on Wikipedia, to get a sense of what is going on under the hood.
The C# is on the client end while Java code is used in a service. Windows phone encrypts the data while Java decrypts the data using the same symmetric key.
Below is my C# method for encryption
public static string EncryptAesTest(string data, string password)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512);
Windows.Security.Cryptography.Core.CryptographicHash Hash_AES = HAP.CreateHash();
string encrypted;
try
{
byte[] hash = new byte[16];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Convert.FromBase64String(password)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(data));
encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));
return encrypted;
}
catch
{
return "encryption error";
}
}
Below is my Java class for decryption
private SecretKeySpec secretKey;
public void setKey() {
skey = "mykey";
MessageDigest sha = null;
try {
key = skey.getBytes("UTF-8");
logger.debug("Key length ====> " + key.length);
sha = MessageDigest.getInstance("SHA-512");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public String decrypt(String strToDecrypt) {
Cipher cipher = null;
try {
cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, this.secretKey);
setDecryptedString(new String(cipher.doFinal(Base64
.decodeBase64(strToDecrypt))));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
The key generation is not complete. For some reason, your C# code uses sets the last byte of the key to the same value as the first byte with the following code:
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
(To my understanding, this could should throw some exception, because you can't copy 16 bytes into the 16 byte array hash if you begin at index 15.)
You could do the same (bad) thing in Java
public void setKey() {
skey = "mykey";
MessageDigest sha = null;
try {
key = skey.getBytes("UTF-8");
logger.debug("Key length ====> " + key.length);
sha = MessageDigest.getInstance("SHA-512");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
key[15] = key[0]; // added
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Things to consider:
ECB mode does not provide semantic security and it should never be used. Use at the very least CBC mode with a random IV for each encryption under the same key.
Passwords should be hashed multiple times. A single hash makes it easy for an attacker to brute-force the password, because this is operation is fast. You should use Password-based Encryption with a strong key derivation function like PBKDF2 (more than 100,000 iterations), scrypt or bcrypt. Don't forget to use a random salt.
Authenticate your ciphertexts. You would want to detect (malicious) manipulations of your ciphertexts in transit. This can be done either with an authenticated mode like GCM or EAX, or with an encrypt-then-MAC scheme by running a MAC algorithm over your ciphertexts. A strong MAC is HMAC-SHA256.