Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedOutputStream;
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.net.Socket;
- import java.net.URL;
- import java.nio.channels.Channels;
- import java.nio.channels.FileChannel;
- import java.nio.channels.ReadableByteChannel;
- import java.security.KeyPair;
- import java.security.KeyPairGenerator;
- import java.security.NoSuchAlgorithmException;
- import java.security.PrivateKey;
- import java.security.PublicKey;
- import javax.crypto.Cipher;
- import org.apache.commons.codec.binary.Base64;
- import org.omg.CORBA.portable.OutputStream;
- public class Client {
- public static final String PUBLIC_KEY_FILE = "C:\\Users\\Neo\\Desktop\\RSA\\klucz.key";
- public static byte[] encrypt(String text, PublicKey key) {
- byte[] cipherText = null;
- try {
- final Cipher cipher = Cipher.getInstance("RSA");
- cipher.init(Cipher.ENCRYPT_MODE, key);
- cipherText = cipher.doFinal(text.getBytes());
- } catch (Exception e) {
- e.printStackTrace();
- }
- return cipherText;
- }
- public static void main(String[] args) throws IOException, ClassNotFoundException {
- try(
- ReadableByteChannel in=Channels.newChannel(
- new URL("http://145.239.90.206/public.key").openStream());
- FileChannel out=new FileOutputStream("C:\\Users\\Neo\\Desktop\\eklucz.key").getChannel() )
- {
- out.transferFrom(in, 0, Long.MAX_VALUE);
- }
- System.out.println("Pobralem klucz publiczny wygenerowany przez serwer (145.239.90.206/klucz.key)");
- try
- {
- final String originalText = "Tajna wiadomosc BT";
- ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("C:\\Users\\Neo\\Desktop\\klucz.key"));
- final PublicKey publicKey = (PublicKey) inputStream.readObject();
- final byte[] cipherText = encrypt(originalText, publicKey);
- String zaszyfrowana_rsa = new Base64().encodeToString(cipherText);
- System.out.println("Zaszyfrowana wiadomosc: " + zaszyfrowana_rsa);
- System.out.println("Wysylam do serwera.");
- Socket clientSocket = new Socket("145.239.90.206", 8888);
- DataOutputStream dOut = new DataOutputStream(clientSocket.getOutputStream()); // wysylamam do serwera
- dOut.writeInt(cipherText.length);
- dOut.write(cipherText);
- clientSocket.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement