Last active
December 1, 2017 09:58
-
-
Save minhphong306/68c9760b37bd4fb11a3b7bb7a107f1c7 to your computer and use it in GitHub Desktop.
Class using RSA to encrypt, decrypt, compare MD5 hash, read and write file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package onthi; | |
import java.math.BigInteger; | |
import java.security.InvalidKeyException; | |
import java.security.MessageDigest; | |
import java.security.PrivateKey; | |
import java.security.PublicKey; | |
import java.util.Base64; | |
import javax.crypto.Cipher; | |
/** | |
* | |
* @author Linh | |
*/ | |
public class MaHoaRSA { | |
private Cipher cipher; | |
public String maHoa(String chuoi_goc, PrivateKey khoa) throws Exception { | |
String chuoi_da_mahoa = ""; | |
cipher = Cipher.getInstance("RSA"); | |
cipher.init(Cipher.ENCRYPT_MODE, khoa); | |
chuoi_da_mahoa = Base64.getEncoder().encodeToString(cipher.doFinal(chuoi_goc.getBytes())); | |
return chuoi_da_mahoa; | |
} | |
public String giaiMa(String chuoi_daduoc_mahoa, PublicKey khoa) throws Exception { | |
String chuoi_daduoc_giaima; | |
cipher = Cipher.getInstance("RSA"); | |
cipher.init(Cipher.DECRYPT_MODE, khoa); | |
chuoi_daduoc_giaima = new String(cipher.doFinal(Base64.getDecoder().decode(chuoi_daduoc_mahoa))); | |
return chuoi_daduoc_giaima; | |
} | |
public String bamMD5(String chuoi_can_bam) throws Exception{ | |
String chuoi_daduoc_bam; | |
MessageDigest md = MessageDigest.getInstance("MD5"); | |
md.update(chuoi_can_bam.getBytes(), 0, chuoi_can_bam.length()); | |
chuoi_daduoc_bam = new BigInteger(1, md.digest()).toString(16); | |
return chuoi_daduoc_bam; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment