Skip to content
Snippets Groups Projects

RemSig password encrypt

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Erik Horváth

    Note: You must change public key data.

    encrypt.java 1.25 KiB
    import javax.crypto.Cipher;
    import java.nio.charset.StandardCharsets;
    import java.security.KeyFactory;
    import java.security.PublicKey;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.Base64;
    
    public class Main {
        private static String pubKey = "-----BEGIN PUBLIC KEY-----\n" +
                "PUBLIC_KEY_DATA" +
                "-----END PUBLIC KEY-----\n" +
                "\n";
    
        public static void main(String[] args) throws Exception {
            if (args.length == 0) {
                System.out.println("Specify password as program argument.");
                return;
            }
            String passwordToEncrypt = args[0];
    
            pubKey = pubKey.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----","");
            PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.getMimeDecoder().decode(pubKey)));
            Cipher encrypt = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            encrypt.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedPassword = encrypt.doFinal(passwordToEncrypt.getBytes(StandardCharsets.UTF_8));
            String result = new String(Base64.getMimeEncoder().encode(encryptedPassword), StandardCharsets.UTF_8).replace("\r", "");
    
            System.out.println(result);
        }
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Please register or to comment