# rsa v1

### Repository

{% embed url="<https://github.com/metadiv-io/rsa/tree/v1>" %}

### Installation

```
go get -u github.com/metadiv-io/rsa
```

### Features

* Generate RSA key pairs with customizable bit sizes (minimum 1024 bits)
* Convenient 4096-bit key generation for long-term security
* PEM encoding/decoding for both public and private keys
* Type-safe key handling with separate PublicKey and PrivateKey types

### Usage

#### Generating New Keys

```go
// Generate a 4096-bit RSA key (recommended for long-term security)
privateKey := rsa.New4096RSAKey()

// Or generate a custom-sized key (minimum 1024 bits)
privateKey, err := rsa.NewRSAKey(2048)
if err != nil {
    // Handle error
}
```

#### Working with Keys

```go
// Get the public key from a private key
publicKey := privateKey.PublicKey()

// Get key sizes
privateBits := privateKey.Size()  // Returns size in bits
publicBytes := publicKey.Size()   // Returns size in bytes

// Export keys as PEM strings
privatePEM := privateKey.Pem()
publicPEM := publicKey.Pem()
```

#### Loading Keys from PEM

```go
// Load a private key from PEM
privateKey, err := rsa.NewPrivateKeyFromPem(pemString)
if err != nil {
    // Handle error
}

// Load a public key from PEM
publicKey, err := rsa.NewPublicKeyFromPem(pemString)
if err != nil {
    // Handle error
}
```

### Error Handling

The package provides several error types for specific validation scenarios:

* `ErrInvalidBitSize`: Returned when the requested key size is not positive or not a multiple of 8
* `ErrBitSizeTooSmall`: Returned when the requested key size is less than 1024 bits
* `ErrInvalidPEM`: Returned when parsing an invalid PEM-encoded public key
* `ErrNotRSAPublicKey`: Returned when the parsed key is not an RSA public key
* `ErrInvalidPrivateKeyPEM`: Returned when parsing an invalid PEM-encoded private key
* `ErrInvalidPrivateKey`: Returned when the parsed private key is invalid

### Security Recommendations

* Use 4096-bit keys (`New4096RSAKey()`) for long-term security beyond 2030
* Never share private keys or store them in plaintext
* Always use secure random number generation (handled automatically by this package)
* Keep your Go version updated to ensure you have the latest security patches
