Java Implementation encryption

Source: Internet
Author: User
Tags crypt decrypt md5 encryption asymmetric encryption

Encryption has one-way encryption and two-way encryption, also known as symmetric and asymmetric encryption, two-way encryption is to encrypt the data, you can also decrypt the original data, but need to use the key, and must be the same key. To decrypt the original data. I don't know at first, the key is a system-generated key, Encryption and decryption when the separate operation, after the encryption, the data will not be decrypted. The Java method of implementing encryption has des,aes, such as symmetric encryption. One-way encryption is not encrypted in the strict sense. Only a certain algorithm is implemented, but it cannot be reversed. MD5 encryption is a one-way asymmetric encryption technique. Directly on the code

Package Com.chen;import Java.security.invalidkeyexception;import javax.crypto.badpaddingexception;import Javax.crypto.cipher;import Javax.crypto.illegalblocksizeexception;import Javax.crypto.keygenerator;import Javax.crypto.secretkey;public class Chen {//Key GeneratorPrivate keygenerator kg =NULL; //secret keyPrivate Secretkey key =NULL; //for encryption and decryptionPrivate Cipher CIP =NULL; Public Chen () throws exception{kg= Keygenerator.getinstance ("DES"); Key=Kg.generatekey (); CIP= Cipher.getinstance ("DES"); } Publicbyte[] Encrypt (byte[] s) throws InvalidKeyException, Illegalblocksizeexception, badpaddingexception{//InitializeCip.init (Cipher.encrypt_mode, key); //Encrypt        returncip.dofinal (s); } Publicbyte[] Decrypt (byte[] b) throws InvalidKeyException, Illegalblocksizeexception, badpaddingexception{//InitializeCip.init (Cipher.decrypt_mode, key); //decryption        returncip.dofinal (b); } public staticvoidMain (string[] args) {Try{Chen Chen=NewChen (); String Str= "ABA Safenstiffen"; //Encrypt            byte[] temp =Chen.encrypt (Str.getbytes ()); //decryption            byte[] flag =Chen.decrypt (temp); System.out.println ("Clear text:" +str); System.out.println ("Encrypted data:" +NewString (temp)); System.out.println ("Decrypted data:" +NewString (flag)); } Catch(Exception e) {e.printstacktrace (); }    }}

AES Encryption and decryption code

 PackageCrypt;Importjava.security.InvalidKeyException;Importjava.security.NoSuchAlgorithmException;Importjavax.crypto.BadPaddingException;ImportJavax.crypto.Cipher;Importjavax.crypto.IllegalBlockSizeException;ImportJavax.crypto.KeyGenerator;Importjavax.crypto.NoSuchPaddingException;ImportJavax.crypto.SecretKey; Public classAescrypt {//Key Generator    Privatekeygenerator kg; //secret key    PrivateSecretkey Key; //Cryptographic Decryption Classes    PrivateCipher Cipher;  PublicAescrypt ()throwsnosuchalgorithmexception, nosuchpaddingexception{kg= Keygenerator.getinstance ("AES");        System.out.println (Kg.getprovider (). GetName ()); Key=Kg.generatekey (); Cipher= Cipher.getinstance ("AES");    System.out.println (Cipher.getprovider ()); }     Public byte[] Encrypt (byte[] b)throwsinvalidkeyexception, illegalblocksizeexception, badpaddingexception{//InitializeCipher.init (Cipher.encrypt_mode, key); returncipher.dofinal (b); }     Public byte[] Decrypt (byte[] b)throwsinvalidkeyexception, illegalblocksizeexception, badpaddingexception{//InitializeCipher.init (Cipher.decrypt_mode, key); //decryption        returncipher.dofinal (b); }     Public Static voidMain (string[] args) {Try{aescrypt AES=NewAescrypt (); String s= "safasf Rice 2342 (& (*"; byte[] temp =Aes.encrypt (S.getbytes ()); byte[] flag =Aes.decrypt (temp); System.out.println ("Clear text:" +s); System.out.println ("Encrypt:" +NewString (temp)); System.out.println ("Decrypt:" +NewString (flag)); } Catch(Exception e) {e.printstacktrace (); }            }}

Asymmetric RSA, with a single key, a public key, a private key, encrypted by one of the keys, decrypted by one of the other keys

 PackageCrypt;Importjava.security.InvalidKeyException; ImportJava.security.KeyPair; ImportJava.security.KeyPairGenerator; Importjava.security.NoSuchAlgorithmException; ImportJava.security.interfaces.RSAPrivateKey; ImportJava.security.interfaces.RSAPublicKey; Importjavax.crypto.BadPaddingException; ImportJavax.crypto.Cipher; Importjavax.crypto.IllegalBlockSizeException; Importjavax.crypto.NoSuchPaddingException;  Public classRsacrypt {/*** Encryption *@paramPublicKey *@paramSrcbytes *@return      * @throwsnosuchalgorithmexception *@throwsnosuchpaddingexception *@throwsInvalidKeyException *@throwsillegalblocksizeexception *@throwsbadpaddingexception*/      protected byte[] Encrypt (Rsapublickey publickey,byte[] srcbytes)throwsnosuchalgorithmexception, Nosuchpaddingexception, InvalidKeyException, Illegalblocksizeexception, badpaddingexception{if(publickey!=NULL){              //Cipher is responsible for completing encryption or decryption work, based on RSACipher Cipher = cipher.getinstance ("RSA"); //Initializes a cipher object based on the public keyCipher.init (Cipher.encrypt_mode, PublicKey); byte[] Resultbytes =cipher.dofinal (srcbytes); returnresultbytes; }          return NULL; }            /*** Decryption *@paramPrivatekey *@paramSrcbytes *@return      * @throwsnosuchalgorithmexception *@throwsnosuchpaddingexception *@throwsInvalidKeyException *@throwsillegalblocksizeexception *@throwsbadpaddingexception*/      protected byte[] Decrypt (Rsaprivatekey Privatekey,byte[] srcbytes)throwsnosuchalgorithmexception, Nosuchpaddingexception, InvalidKeyException, Illegalblocksizeexception, badpaddingexception{if(privatekey!=NULL){              //Cipher is responsible for completing encryption or decryption work, based on RSACipher Cipher = cipher.getinstance ("RSA"); //Initializes a cipher object based on the public keyCipher.init (Cipher.decrypt_mode, Privatekey); byte[] Resultbytes =cipher.dofinal (srcbytes); returnresultbytes; }          return NULL; }        /**      * @paramargs *@throwsnosuchalgorithmexception *@throwsbadpaddingexception *@throwsillegalblocksizeexception *@throwsnosuchpaddingexception *@throwsinvalidkeyexception*/       Public Static voidMain (string[] args)throwsnosuchalgorithmexception, InvalidKeyException, Nosuchpaddingexception, Illegalblocksizeexception, badpaddingexception {rsacrypt RSA=NewRsacrypt (); String msg= "Guo xx-boutique crosstalk"; //The Keypairgenerator class is used to generate public and private key pairs, generating objects based on the RSA algorithmKeypairgenerator Keypairgen = keypairgenerator.getinstance ("RSA"); //initializes the key pair generator with a key size of 1024 bitsKeypairgen.initialize (1024); //generate a key pair, saved in KeyPairKeyPair KeyPair =Keypairgen.generatekeypair (); //get the private keyRsaprivatekey Privatekey =(Rsaprivatekey) keypair.getprivate (); //get the public keyRsapublickey PublicKey =(Rsapublickey) keypair.getpublic (); //encrypt with public key        byte[] Srcbytes =msg.getbytes (); byte[] Resultbytes =Rsa.encrypt (PublicKey, srcbytes); //decrypt with private key        byte[] Decbytes =Rsa.decrypt (Privatekey, resultbytes); System.out.println ("Clear Text is:" +msg); System.out.println ("After encryption is:" +NewString (resultbytes)); System.out.println ("After decryption is:" +NewString (decbytes)); }    }  

Java Implementation encryption

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.