REGEXVAULTv2.0
Security/Certificates & PKI
Verified Safe

SSH Public Key Regex for Java

/^(ssh-rsa|ssh-ed25519|ssh-ecdsa|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)\s+([A-Za-z0-9+/]{20,800}(?:={0,3}))(?:\s+(.+))?$/

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching ssh public key, ported and verified for Java. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.

Java Implementation

Java
// SSH Public Key
// ReDoS-safe | RegexVault — Security > Certificates & PKI

import java.util.regex.Pattern;

public class SshPublicKeyValidator {
    private static final Pattern PATTERN =
        Pattern.compile("^(ssh-rsa|ssh-ed25519|ssh-ecdsa|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521|sk-ssh-ed25519@openssh\\.com|sk-ecdsa-sha2-nistp256@openssh\\.com)\\s+([A-Za-z0-9+/]{20,800}(?:={0,3}))(?:\\s+(.+))?$");

    public static boolean validate(String input) {
        return PATTERN.matcher(input).matches();
    }

    // Example
    public static void main(String[] args) {
        System.out.println(validate("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl user@host")); // true
    }
}

Test Cases

Matches (Valid)
Rejects (Invalid)
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl user@hostssh-rsa short
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC0 user@machinersa AAAAB3NzaC1yc2EAAA
ssh-rsa AAAA@#$% user@host

When to use this pattern

This pattern is drawn from the Security > Certificates & PKI category and carries a ReDoS-safe certification. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.

Common Pitfalls

RSA keys below 3072 bits should be considered deprecated per NIST SP 800-186. Ed25519 is preferred for its small key size, fast operations, and resistance to weak random number generation during signing.

Technical Notes

Capture groups: 1=key type, 2=base64 key material, 3=comment (optional, usually user@host). Supported types: RSA (deprecated), Ed25519 (preferred), ECDSA (nistp256/384/521), SK (FIDO2 hardware key variants). Prefer Ed25519 for new SSH keys.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern