Take a look at the pem file:
View attachment 50552
1. It looks like a Base64-String
2. There's a header and a footer (which is not Base64)
3. There are LF's at the end of each line (which is not Base64, too)
What we need is a clean Base64 string:
Dim Pem As String
Dim PemBytes() As Byte
Pem=File.ReadString(File.DirApp,"pem.pem") 'read the pem file into a string
Pem=Pem.Replace("-----BEGIN PRIVATE KEY-----","")
Pem=Pem.Replace("-----END PRIVATE KEY-----","")
Pem=Pem.Replace(CRLF,"")
After this it is:
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDx4a//WIdrQfPjKMlNCXSHuISFd7CkIkqPN14EKbEC9EvsA59Ct6qy4jkG8LaajcX07bOSdJVkNMpjLsNE8sTdS4MNjwkcsmqjnMpnKCcR0UKwnShTZyUjevceFSeiopWEZ2LS91qPL0dg1S5NCgV/ds0E5jcx/KRsdwS35npjzRWnV4gFwCcVOKXm/3L5lRBB+y6PT2P9bRGKctusOlkuImK1BT8o0/ohATnlLB7uEfB+AuFJwYP/KUYVSYGNjuBklh1wCjhuMsGWeoU2uZcrN8F7D/jKZ/nsKefVABw6ELP0NP9EsHZSQ/i77szP1NjxdOAW5qdlsPNtEDE3th9pAgMBAAECggEAaIp3i7ASj0vpAePt5OrSP5qDREAvyzC68t0mODxgsfsuGSqTmb1R/JCDvzkoYvIlfa+CrijPLIkYc/eRE+qtJUvur1yDvrBq...
This is a clean Base64-string
1. Convert it into Bytes
2. Load it
Full code:
Dim Pem As String
Dim PemBytes() As Byte
Pem=File.ReadString(File.DirApp,"pem.pem") 'load from file into string
Pem=Pem.Replace("-----BEGIN PRIVATE KEY-----","")
Pem=Pem.Replace("-----END PRIVATE KEY-----","")
Pem=Pem.Replace(CRLF,"")
Log(Pem)
Dim su As StringUtils
PemBytes=su.DecodeBase64(Pem) 'Base64 -> Bytes
Dim TestC As Cipher
Dim TestKPG As KeyPairGenerator
TestC.Initialize("RSA/ECB/PKCS1Padding")
TestKPG.Initialize("RSA", 2048)
TestKPG.PrivateKeyFromBytes(PemBytes) 'Works!
Note: Usually you get the PUBLIC key, not the private one (you encrypt with it and it is DEcrypted with the private key). So if two programs use it, there will be 2 Public- and 2 Private Keys!