Skip to content

Instantly share code, notes, and snippets.

@minhphong306
Last active December 1, 2017 09:11
Show Gist options
  • Save minhphong306/7411063b934eaa1ed8caaa728fd84764 to your computer and use it in GitHub Desktop.
Save minhphong306/7411063b934eaa1ed8caaa728fd84764 to your computer and use it in GitHub Desktop.
Class generate key RSA
/*
* 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.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.KeyGenerator;
/**
*
* @author SeVenT
*/
public class SinhKhoaRSA {
private KeyPairGenerator keygen;
private KeyPair keypair;
private PublicKey pubkey;
private PrivateKey prikey;
public SinhKhoaRSA(int dodai) throws Exception {
keygen = KeyPairGenerator.getInstance("RSA");
keygen.initialize(dodai);
keypair = keygen.generateKeyPair();
pubkey = keypair.getPublic();
prikey = keypair.getPrivate();
}
public void ghifile(String duong_dan, byte[] du_lieu) throws Exception {
File f = new File(duong_dan);
f.getParentFile().mkdir();
FileOutputStream fo = new FileOutputStream(f);
fo.write(du_lieu);
fo.flush();
fo.close();
}
public byte[] docfile(String duong_dan) throws IOException {
byte[] bytes;
File file = new File(duong_dan);
bytes = Files.readAllBytes(file.toPath());
return bytes;
}
public PublicKey sinhKhoaCongKhai(byte[] du_lieu) throws Exception{
PublicKey khoa_cong_khai;
X509EncodedKeySpec spec = new X509EncodedKeySpec(du_lieu);
KeyFactory bo_sinh_khoa = KeyFactory.getInstance("RSA");
khoa_cong_khai = bo_sinh_khoa.generatePublic(spec);
return khoa_cong_khai;
}
public PrivateKey sinhKhoaBiMat(byte[] du_lieu) throws Exception{
PrivateKey khoa_bi_mat;
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(du_lieu);
KeyFactory bo_sinh_khoa = KeyFactory.getInstance("RSA");
khoa_bi_mat = bo_sinh_khoa.generatePrivate(spec);
return khoa_bi_mat;
}
public PublicKey getPub() {
return pubkey;
}
public PrivateKey getPri() {
return prikey;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment