Decrypted RSA result not matching the signed message - java

I used Bouncy Castle Crypto APIs to decrypt a cipher text, and verify the signed message.
The signed message:
signedMessageOther: D0F39F8C8495CA83D2F24536083CCB280CD3A54B
The message decrypted:
01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFF003021300906052B0E03021A05000414D0F39F8C8495CA83D2F2453608
3CCB280CD3A54B
Only the last 20 bytes match the signedMessageOther.
Why?
Here is something about the key:
Algorithm: RSA
Format: X.509
Key Length: 162
The key is 162 bytes -1024 bi, so it is a vaild key.
Here is the code:
import java.security.PublicKey;
import java.security.Security;
import javax.crypto.Cipher;
public class DecyrptTest {
public static void main (String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//msg is some secret msg ,i have deleted.
String msg = "";
byte[] signedMsgBytes = SHA1.sign(msg);
String signedMessageOther=StringTools.bytesToHex(signedMsgBytes);
System.out.println("signedMessageOther: "+signedMessageOther);
String ct="1386cfed01490b9026903722324f80f8a56cc38169b46e15154ce9e7168ff589282855002e195a0c1a96d5fe540a7fa97b01ae24f365f39302e0c1186ee9308d6b94526741f7093dc2678c713bb2b1a8a6942decb35b16725353da523417cb835cea903485b19b63c2c444c8bc6c865ea78c749f10ca70b266f6078192f5c76c";
Cipher cipher = Cipher.getInstance("RSA", "BC");
PublicKey pubKey = KeyUtil.getPubKeyFromFile("res/key.pub");
System.out.println("Algorithm: "+pubKey.getAlgorithm());
System.out.println("Format: "+pubKey.getFormat());
System.out.println("Key Length: "+pubKey.getEncoded().length);
cipher.init(Cipher.DECRYPT_MODE, pubKey);
byte[] ctBytes=StringTools.hexStringToByteArray(ct);
System.out.println(ctBytes.length);
byte[] cipherText2 = cipher.doFinal(ctBytes);
System.out.println("cipher: " + StringTools.bytesToHex(cipherText2));
}
}

You are are trying to drive to work with an internal combustion engine. You need a car.
RSA is a primitive operation that can be pieced with other things to make a useful encryption system. You can't just use it by itself to do the whole job.
I'm not sure if that's really saying the key is 162 bits, but if so, that's a completely useless RSA key size. An RSA key has to be at least 384 bits to be of any use at all. Also, RSA can't sign or encrypt data larger than the key. 162 bits is about 20 bytes. Sound familiar?
You can't use an engine to drive to work. You need a car. RSA is an engine.

Related

encrypt files with AES , with shared password

I want to encrypt/ decrypt with AES, with shared passwod, my code same as here.
the linked code works fine, but there is no shared passworn in it.
how can I add a shared password to the following implementation?
I need something like
String shared="xxx..";//some password with 16 digits length
Is it possible?
and adding this shared password to the encryption.
It is very important that the key used for AES encryption is not easy to guess so in a lot of implementations the keys are generated randomly. The key itself is a byte array of 16 (128 bit), 24 (192 bit) or 32 (256 bit) byte length and a byte array is not usuable as source for a shared password.
The solution is to encode the byte array into a Base64-encoded string and pass this string to the recepient on a secure way. The recepient decodes the string back to a byte array and further via the SecretKeySpec to a secret key.
The small example shows the way to securly generate a random password with different lengths (the example uses only the 128 bit keylength, encode it and decode it back to a secret key - the orginal SecretKey k is compared to the regenerated SecretKex kReceived.
Just a last notice but it is a security warning: Your encryption method is using the AES ECB mode that is unsecure - please do not use this mode in production (mode is defined here: AES/ECB/PKCS5Padding).
Result:
https://stackoverflow.com/questions/62782129/encrypt-files-with-aes-with-shared-password
sharedKey: UT7PPJwX2fnYTazSOZAhxg==
keySpecReceived equals secretKey: true
Code:
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException {
System.out.println("https://stackoverflow.com/questions/62782129/encrypt-files-with-aes-with-shared-password");
// random key creation taken from https://stackoverflow.com/a/41414233/9114020
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = new SecureRandom();
int keyBitSize = 128; // aes keylength can be 128, 192 or 256 bit
keyGenerator.init(keyBitSize, secureRandom);
SecretKey k = keyGenerator.generateKey();
// encode the key and then base64-encoding
String sharedKey = Base64.getEncoder().encodeToString(k.getEncoded());
System.out.println("sharedKey: " + sharedKey);
// share this key with another party on a secure way
String sharedKeyReceived = sharedKey; // simulates the receiving
byte[] sharedKeyByteReceived = Base64.getDecoder().decode(sharedKeyReceived);
SecretKeySpec kReceived = new SecretKeySpec(sharedKeyByteReceived, "AES");
System.out.println("keySpecReceived equals secretKey: " + kReceived.equals(k));
}
}

RSA and AES for encrypt and decrypt a plainText (verify key)

I want to ask you some question about security on key in java. My code using RSA and AES for encrypt and decrypt a plainText. And I want to use my own password as a private key(AES) for verifies key(RSA). Because RSA are generate public and private key random. (In real case: private key is input by user and public key store in database for verification.)
This code is work find, but I want to know this code is correct or not? Please advice! Thank you.
My process:
1. generate a symmetric key
2. Encrypt the data with the symmetric key
3. Encrypt the symmetric key with rsa
4. send the encrypted key and the data
5. Decrypt the encrypted symmetric key with rsa
6. decrypt the data with the symmetric key
7. done
import java.io.UnsupportedEncodingException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AES_RSA {
private static byte[] key;
private static SecretKeySpec secretKey;
public static void main(String[] args){
try {
//1. Generate Symmetric Key (AES with 128 bits)
String password = "123456";
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128); // The AES key size in number of bits
setKey(password);
//2. Encrypt plain text using AES
String plainText = "Please encrypt me urgently...";
Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
//3. Encrypt the key using RSA public key
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
PublicKey puKey = keyPair.getPublic();
PrivateKey prKey = keyPair.getPrivate();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.PUBLIC_KEY, puKey);
byte[] encryptedKey = cipher.doFinal(secretKey.getEncoded()/*Seceret Key From Step 1*/);
//4. Send encrypted data (byteCipherText) + encrypted AES Key (encryptedKey)
//5. On the client side, decrypt symmetric key using RSA private key
cipher.init(Cipher.PRIVATE_KEY, prKey);
byte[] decryptedKey = cipher.doFinal(encryptedKey);
//6. Decrypt the cipher using decrypted symmetric key
SecretKey originalKey = new SecretKeySpec(decryptedKey , 0, decryptedKey.length, "AES");
Cipher aesCipher1 = Cipher.getInstance("AES/ECB/PKCS5PADDING");
aesCipher1.init(Cipher.DECRYPT_MODE, originalKey);
byte[] bytePlainText = aesCipher1.doFinal(byteCipherText);
String plainText1 = new String(bytePlainText);
//7. Done! 'Please encrypt me urgently...'
System.out.println(plainText1);
}catch (Exception e) {}
}
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-256");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
You pseudo-steps are correct, but your description not. For example, you normally keep RSA private key and distribute RSA public key.
But a few suggestions for creating better code.
I suggest to use PKCS5 for creating password-based secret keys rather than a simple hash. Java's PBEKeySpec is a class for generating such secret keys. Here is a small sample code which you can use for your setKey() routine (adjust it as you prefer):
SecretKeyFactory skf = SecretKeyFactory.getInstance("AES");
SecretKey key = skf.generateSecret(new PBEKeySpec(password.getBytes("UTF-8"), salt, 10000));
Never use ECB mode of operation for encrypting data. In worse case, use CBC with randomized IV.
You got something wrong. RSA private key is kept private on server, but RSA public key is distributed freely between clients(normally). You are doing this in the other way.
This is just a suggestion, but I think it is better to use RSA/ECB/OAEPWithSHA-256AndMGF1Padding rather than RSA/ECB/PKCS1Padding for RSA padding. But I think it is not necessary.
In general, you must add a hash or HMAC for authenticating your encrypted data too. But you don't have any authenticating mechanism right now.
Update: Based on design of your mechanism, you cannot securely add an authentication method for detecting active attacks(such as man-in-the-middle). Check comments from Maarten too.
These are the problems that I found. The most important one is just using RSA key-pair in an incorrect way.

AES Encryption in android and decryption in nodejs

I was trying encryption in android and decryption in nodejs server. I generated an AES 128bit key and encrypt it using AES algorithm and then encrypt this generated key using RSA algorithm. Then send both to the server. But while decrypting on the server side, I think the RSA decryption works fine but have a problem in AES decryption.
I'm not getting the string in server side that I encrypted on the client side.
This is the code for the encryption on android side:
String encryptedSecretKey;
String cipherTextString;
// 1. generate secret key using AES
KeyGenerator keyGenerator = null;
keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
// 2. get string which needs to be encrypted
String text = "This is the message to be encrypted";
// 3. encrypt string using secret key
byte[] raw = secretKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
cipherTextString = Base64.encodeToString(cipher.doFinal(text.getBytes(Charset.forName("UTF-8"))), Base64.DEFAULT);
// 4. get public key
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(Base64.decode(publicKeyString, Base64.DEFAULT));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(publicSpec);
// 5. encrypt secret key using public key
Cipher cipher2 = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher2.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedSecretKey = Base64.encodeToString(cipher2.doFinal(secretKey.getEncoded()), Base64.DEFAULT);
Then send this to the server side.
The code for server side is given below:
var encryptedMessage = req.body.cipherText;
var encryptedAesKey = req.body.secretKey;
//printing those values
console.log("\nEncryptedMessage: \n" + encryptedMessage);
console.log("\nEncrypted key: \n" + encryptedAesKey);
var privateKey = fs.readFileSync('././Keys/privkey_server.pem', "utf8");
var bufferForAesKey = new Buffer(encryptedAesKey, "base64");
var obj = {
key: privateKey
// , padding: constants.RSA_PKCS1_PADDING
// , padding: constants.RSA/ECB/OAEPWithSHA-1
};
var decryptedAes = crypto.privateDecrypt(obj, bufferForAesKey);
console.log("Decrypted AES: " + decryptedAes);
var decryptedAesKeyString = decryptedAes.toString("base64");
console.log("Decrypted AES Key: " + decryptedAesKeyString);
var bufferForAES = new Buffer(decryptedAes, "base64");
//decrypting using AES
var bufferForEncryptedMsg = new Buffer(encryptedMessage, "base64");
var decipher = crypto.createDecipher('aes-128-cbc',bufferForAES);
decipher.setAutoPadding(false);
var dec = decipher.update(bufferForEncryptedMsg,"base64", "utf8");
dec += decipher.final("utf8");
console.log(dec);
Here the final result 'dec' is not giving the correct result but the intermediate results are same in client and server. That means, RSA works fine but have problem in AES.
The output is given below:
EncryptedMessage:
SfosHg+cTrQXYUdF0FuqCJMHgfcP13ckp2L0B9QqOcl8UtWnnl8fLi5lxgR2SKOj
Encrypted key:
C/pa52PZda3xShrPXkHZx8OL6sW4JBEhG/ggNAoHhSVXIGt+iDq/B1ByG5yStBGF3GFJRQT0aGsG
+bZJydP7j9gTivmt99H/bxiZan4CHZnqfGKG1dJCI7ILAYZMCw7JhIcRC8qHMM4LMdF+rxRhENDe
alUfnsLWpcrX9J6fKejJ7EWnWQ1VadKqCDmrJ5xw0lBbsOpwN/vY09+VhF4WkOz8Y3cQGk+FVdz5
tr4L9/jgXlTZdOC2KVBLSH+9pvtHwMWFKKoDSAzvkil4htBjbWTqlBuEINC4I/J/4P3RX2riT5Pv
xHQi/Dv7vdBlo9AEdvWe3Ek8oBleIpmIQHXwQWknPOYghhBAVmACG/tbEQcAtbcmRLruT/XzjPJt
HNBt2HeG9JHYKNoHC3kOuJdnlGe8mv8k0Nzwj04RhEGKSmPIiu/oDgYwS0l96KIlS2ELqBlS5O0L
AJ+RBG7m0WwC9dfrufsuwu0+SPUmg5/ElXRmA3T81lXtQqQbGg8G6r/bAVFGduy4a49s/VWoylx+
/sI079IwyY0IOfwQTVGZRyDC5O1ZBjoYv2+TRo3bjG8GXNQoybkmWkhgotcqVD9mXO67D2NBsFPT
EJnw+1ApSqR7ggIAF+qsMxejFKBICBL/4J8FP4+obA07J1pWiciTRKX+G130qzIBKM08Zdaf/50=
Decrypted AES: %Kp[ϪS�/�W l��9ӊ˽��~��
B�A�
Decrypted AES Key: JUtwW8+qU6Mv/FcgbMbkOdOKy72pun4B490KQrRB4QQ=
T�Ϝ��u��q�
���w�p���u`�̗r[`H0[tW��=��~i-�W
Here the Decrypted AES key is same as the key that we generate in android. But the final output is not giving the desired result. Is there any error in my code??
Neardupe Decrypting strings from node.js in Java? which is the same thing in the opposite direction.
[In Java] I generated an AES 128bit key and encrypt [with] it using AES algorithm and then encrypt this generated key using RSA algorithm.
No you didn't. Your Java code instantiates a KeyGenerator for AES-128, but doesn't use it to generate any key. The key you actually used (and as you say the server correctly decrypted from RSA-OAEP) is 32 bytes, corresponding to AES-256.
But your main problem is that createDecipher takes a password NOT the key. Per the doc
crypto.createDecipher(algorithm, password[, options])
The implementation of crypto.createDecipher() derives keys using the OpenSSL function EVP_BytesToKey with the digest algorithm set to MD5, one iteration, and no salt.
You passed what is actually a key as a password; this results in nodejs using a key that is completely different from the one used in Java and thus getting completely wrong results. You should instead use createDecipheriv which does take the key, and IV (Initialization Vector).
And that is your other problem. To decrypt you must use the same IV as encrypt did, normally by including the IV with the ciphertext sent from the sender to receiver, but you don't. As a result the following (simplified) code cannot decrypt the first 16 bytes of your data, but does the rest.
const crypto = require('crypto');
msg = Buffer.from('SfosHg+cTrQXYUdF0FuqCJMHgfcP13ckp2L0B9QqOcl8UtWnnl8fLi5lxgR2SKOj','base64');
aeskey = Buffer.from('JUtwW8+qU6Mv/FcgbMbkOdOKy72pun4B490KQrRB4QQ=','base64');
dec = crypto.createDecipheriv('aes-256-cbc',aeskey,Buffer.alloc(16)/*this should be the IV*/);
console.log(dec.update(msg,'','latin1')+dec.final('latin1'));
// I used latin1 instead of utf8 because the garbaged first block
// isn't valid UTF-8, and the rest is ASCII which works as either.
->
Y;øï«*M2WÚâeage to be encrypted
// some garbaged chars are control chars and Stack (or browser?)
// may not display them but there really are 16 in total
As an aside, the statement in the doc that 'Initialization vectors [must] be unpredictable and unique ... [but not secret]' is correct for CBC mode, but not some other modes supported by OpenSSL (thus nodejs) and Java. However, that's not a programming Q and thus offtopic here; it belongs on crypto.SX or possibly security.SX where it has already been answered many times.

Encrypt a SecretKey with RSA in Java

I'm working on a client-server secure protocol where I need to use RSA in Java to encrypt a SecretKey for HMAC digests because the key has to be sent to the server. The encryption has two stages; first, I need to encrypt the symmetric key with a public asymmetric key, then, that encrypted message is encrypted with a private asymmetric key.
For this purpose I generate the SecretKey as:
public SecretKey generate(){
KeyGenerator generator = KeyGenerator.getInstance("HMACSHA256");
k = generator.generateKey();
return k;
}
Later, I use this code to encrypt any byte array with a public key:
public byte[] encryptPublic(PublicKey key, byte[] array){
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(array);
return encrypted;
}
The code for encryption with a private key is the same but using a private key.
For the RSA encryption I'm using 1024 bit long asymmetric keys so I have two main questions:
How can I turn my SecretKey to a byte array in order to encrypt it with RSA and a public key?
As the public key encryption produces a byte array with 128 bytes, how can I encrypt that message again with a private key if the key is 1024 bits long and can only encrypt a 117 byte long message?
How can I turn my SecretKey to a byte array in order to encrypt it with RSA and a public key?
That's called wrapping:
public static byte[] wrapKey(PublicKey pubKey, SecretKey symKey)
throws InvalidKeyException, IllegalBlockSizeException {
try {
final Cipher cipher = Cipher
.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher.init(Cipher.WRAP_MODE, pubKey);
final byte[] wrapped = cipher.wrap(symKey);
return wrapped;
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new IllegalStateException(
"Java runtime does not support RSA/ECB/OAEPWithSHA1AndMGF1Padding",
e);
}
}
Note that this explicitly doesn't convert to byte[] first. That's because the key might well be within e.g. a hardware security module. In a HSM the wrapping may be possible, but the conversion to byte[] in local memory would usually not be possible.
As the public key encryption produces a byte array with 128 bytes, how can I encrypt that message again with a private key if the key is 1024 bits long and can only encrypt a 117 byte long message?
You shouldn't do this and you cannot do this either. The reason that you shouldn't do it because encryption with the private key does not provide confidentiality, as anybody would have access to the public key.
Padding is required to perform secure RSA encryption. The padding overhead (of 11 bytes for PKCS#1 v1.5 style padding) is there prohibiting you to encrypt with the private key.
Note that the entire operation: encryption with a private key isn't even specified in PKCS#1 - it's not a legit operation.
Usually the much more secure ephemeral-ephemeral (EC)DH is used to establish keys in transport protocols, using the private key(s) only for authentication. You may want to take a hint from the (draft versions of) TLS 1.3. Or you may just want to use TLS or the handshake portion of it.

Hybrid encryption approach fails

Im having trouble with my attempt to create a small programme using hybrid encryption with AES and RSA. It works just fine using only symmetric encryption AES which i have tried, but when i try to implement RSA to wrap the AES encrypted message and key i just cant get it to work.
I have understood that a programme like this can be done using outputstreams or cipherstreams but I´d like to solve it this way if it is possible. In other words id like a user to enter any string into the JOptionInputDialog and get it encrypted with AES key and then the AES key encrpyted with RSA public key and then decrypted with a private RSA key.
I want the answer to display in the same JOptionPane window. In example :
The encrypted text : jfjfjh
The decrypted text : Hello
I have issues right now understanding how to get that string decrypted with the private RSA key. I dont know what i am missing or doing wrong. From any examples ive been googling for the past week and a half i think it looks fine. I must be missing something that is right infront of my eyes but i cant see it since i sit up for too many hours trying to find a different approach ( i think ive changed it a million times but i cant show you all my approaches so this is the one i share with you. Id be really thankful for any kind of help. So here is my code: (Hope you can understand as some words are in my language)
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.swing.JOptionPane;
/**
*
* #author Patricia
*/
public class EncryptionDecryption {
/**
* #param args the command line arguments
* #throws java.lang.Exception
*/
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
//Creating assymmetric keys RSA ( A public Key and Private Key )
KeyPairGenerator gen2 = KeyPairGenerator.getInstance("RSA");
gen2.initialize(1024);
KeyPair keyPair = gen2.genKeyPair();
PrivateKey privatnyckel = keyPair.getPrivate();
PublicKey publiknyckel = keyPair.getPublic();
//Create assymmetric key AES //Create key generator
KeyGenerator gen = KeyGenerator.getInstance("AES"); //Returns keygenerator object that generates key for specified algorithm in this case AES
SecureRandom random = new SecureRandom();
gen.init(random);
// create a key
SecretKey AES = gen.generateKey();
//get the raw key bytes
byte[] symmetriskNyckel =AES.getEncoded(); //Returns copy of the key bytes
//Create cipher based upon AES, encrypt the message with AES key
Cipher cipher = Cipher.getInstance("AES");
//Initialize cipher with secret key AES
cipher.init(Cipher.ENCRYPT_MODE, AES);
// get the text to encrypt with AES key
String inputText1 = JOptionPane.showInputDialog(" Enter the secret message");
//Encrypt the plaintext message you wanna send with the symmetric key AES;
byte[] kryptera = cipher.doFinal(inputText1.getBytes());
//encrypt AES key with RSA
Cipher pipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
pipher.init(Cipher.WRAP_MODE, publiknyckel);
byte[] krypteradAESNyckel = cipher.wrap(AES);
JOptionPane.showMessageDialog(null, "AES key encrypted with RSA public key " + krypteradAESNyckel);
// re-initialise the cipher to be in decrypt mode
Cipher flipher = Cipher.getInstance("RSA");
flipher.init(Cipher.UNWRAP_MODE, privatnyckel );
// decrypt message
byte [] dekryptera = flipher.unwrap(kryptera);
JOptionPane.showMessageDialog
(null, "AES symmetrisk nyckel " +symmetriskNyckel );
// and display the results //
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
"Texten krypterad " + new String(kryptera) + "\n"
+ "Text dekrypterat: " + new String(dekryptera));
JOptionPane.showMessageDialog(null, "\n RSA assymmetrisk privat nyckel " + privatnyckel
+ "RSA assymmetrisk publik nyckel" + publiknyckel);
// end example
System.exit(0);
}
}
I think your variable names and comments are fine to start with. When working with something new, write notes to yourself in the code. You can come back later once it works and refactor with rich, meaningful names, and trim the comments for clarity, so that they speak to you six months or a year from now to remind you of what you were thinking of at the time that you wrote this. (And I think Swedish names are just as good as English.)
As JB Nizet points out, you are unwrapping kryptera when you should be unwrapping the symmetric key contained in krypteradAESNyckel. Next, you would decrypt kryptera with the recovered symmetric key. (Your code justs outputs the earlier symmetriskNyckel without having actually unwrapped it freshly from krypteradAESNyckel.)
I also notice that in one case you
Cipher.getInstance("RSA/ECB/PKCS1Padding");
but later you
Cipher.getInstance("RSA");
I would make them consistent, both "RSA/ECB/PKCS1Padding". This attention to detail is just as important as clear variable names and meaningful comments.

Categories

Resources