Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Java
public class Encryp {
public static void main(String[]args)throws Exception{
KeyGenerator k1=KeyGenerator.getInstance("AES");
k1.init(128);
SecretKey s1=Test.decodekey("IvIdMZRVVbbN2DqjEdVesg==");
    Cipher ciper = Cipher.getInstance("AES");
String plaintext="sid happy";
    System.out.println("text"+plaintext);
    String encry=encrypt(plaintext,s1,ciper);
    System.out.println("after encryption "+encry);

    SecretKey s2=Test.decodekey("IvIdMZRVVbbN2DqjEdVesg==");;
     String decry=decrypt(plaintext,s2,ciper);
    System.out.println("after decryption "+decry);

}

public static String encrypt(String plaintext, SecretKey s1,Cipher ciper) throws Exception{
 byte[] plntxtbyt=plaintext.getBytes();
 ciper.init(Cipher.ENCRYPT_MODE, s1);
 byte[] encrypbyt=ciper.doFinal(plntxtbyt);
    String enc = DatatypeConverter.printBase64Binary(encrypbyt);


    return enc;

}

public static String decrypt(String enc, SecretKey s1,Cipher ciper) throws Exception{
   byte[]decod=DatatypeConverter.parseBase64Binary(enc);
           System.out.println("after decryption "+decod.length);
           ciper.init(Cipher.DECRYPT_MODE, s1);
           byte[] encrypbyt=ciper.doFinal(decod);
            return new String(encrypbyt);

}


What I have tried:

I am seeking a brief explanation about this code. My question is about Java encryption and decryption - what exactly does the code do? Why here use predefine secret key?
Posted
Comments
Richard MacCutchan 26-Jun-16 8:17am    
Encryption always requires a key to convert plain data to encrypted. In most instances the code would request the key from the user, rather than hard code it as above.
Sergey Alexandrovich Kryukov 26-Jun-16 9:35am    
Right. Without description of the scenario, the question makes little to no sense. It should be made clear who gets access to what and who is blocked to access, what action should give the access, and so on.
—SA
Richard MacCutchan 26-Jun-16 12:12pm    
NSS.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900