Created
January 5, 2023 13:15
-
-
Save queerzard/89f48db9efca02f5652ebb9878a493b7 to your computer and use it in GitHub Desktop.
End to End Encryption
This file contains 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
import java.security.*; | |
import java.security.spec.X509EncodedKeySpec; | |
import java.util.Base64; | |
import javax.crypto.Cipher; | |
public class E2EE { | |
private KeyPair keyPair; | |
private String publicKey; | |
private String privateKey; | |
public E2EE() throws NoSuchAlgorithmException { | |
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); | |
keyGen.initialize(2048); | |
keyPair = keyGen.generateKeyPair(); | |
publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()); | |
privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()); | |
} | |
public String getPublicKey() { | |
return publicKey; | |
} | |
public String getPrivateKey() { | |
return privateKey; | |
} | |
public byte[] encrypt(String publicKey, byte[] message) throws Exception { | |
// Decode the public key from base64 | |
byte[] decodedPublicKey = Base64.getDecoder().decode(publicKey); | |
PublicKey key = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decodedPublicKey)); | |
Cipher cipher = Cipher.getInstance("RSA"); | |
cipher.init(Cipher.ENCRYPT_MODE, key); | |
return cipher.doFinal(message); | |
} | |
public byte[] decrypt(byte[] message) throws Exception { | |
Cipher cipher = Cipher.getInstance("RSA"); | |
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); | |
return cipher.doFinal(message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment