1

I am using scala 2.13 and have a string like this:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAtp/Uo28kOjROL50aajnpK25CJoVoic2bqqu6OS2baWWD9fT2
ESqq8mbFxYN3O7JXbs+74YpTdg1jSUALOz9zj/H2eCF71QYvoHmdoi0iiQuy3gS1
6YczVvBvinSwfEnO6Wi/Xx6AC8urdr==
-----END RSA PRIVATE KEY-----

and I want to extract out

MIIEpAIBAAKCAQEAtp/Uo28kOjROL50aajnpK25CJoVoic2bqqu6OS2baWWD9fT2
ESqq8mbFxYN3O7JXbs+74YpTdg1jSUALOz9zj/H2eCF71QYvoHmdoi0iiQuy3gS1
6YczVvBvinSwfEnO6Wi/Xx6AC8urdr==

I am using it as follows:

val privateKey =
  "-----BEGIN RSA PRIVATE KEY-----\r\nMIIEpAIBAAKCAQEAtp/Uo28kOjROL50aajnpK25CJoVoic2bqqu6OS2baWWD9fT2ESqq8mbFxYN3O7JXbs+74YpTdg1jSUALOz9zj/H2eCF71QYvoHmdoi0iiQuy3gS16YczVvBvinSwfEnO6Wi/Xx6AC8urdr==\r\n-----END RSA PRIVATE KEY-----\r\n"

val result = privateKey match {
  case s"-----BEGIN RSA PRIVATE KEY-----\r\n$privateKeyB64\r\n-----END RSA PRIVATE KEY-----\r\n" => privateKeyB64
  case _ => {
    throw AEMServiceAccountError(s"Invalid RSA Private Key - Please check service account credentials for AEM.")
  }
}
println(result)

but the above code always throws Invalid RSA Private Key - Please check service account credentials for AEM.

Can someone help me debug what am I doing wrong here?

2 Answers 2

3

Perhaps reason is in call unapply in pattern matching. It works with regex

val regex = "-----BEGIN RSA PRIVATE KEY-----\r\n(.*)\r\n-----END RSA PRIVATE KEY-----\r\n".r
val result = privateKey match {
  case regex(privateKeyB64) => privateKeyB64
  case _ => throw AEMServiceAccountError(s"Invalid RSA Private Key - Please check service account credentials for AEM.")
}
Sign up to request clarification or add additional context in comments.

Comments

1

Extracting the variable outside solves the issue. Not sure why it doesn't work inlined.

val expectedPrivateKey = s"-----BEGIN RSA PRIVATE KEY-----\r\n$privateKeyB64\r\n-----END RSA PRIVATE KEY-----\r\n"

val result = privateKey match {
  case `expectedPrivateKey` => privateKeyB64
  case _ => {
    throw AEMServiceAccountError(s"Invalid RSA Private Key - Please check service account credentials for AEM.")
  }
}

2 Comments

Hmm that's wierd... :/ would love an explaination for this from someone
I would be interested to know as well. I feel like maybe something obvious is staring us in the face and we aren't seeing it. You might try minimizing it to see how simple the string can be and still demonstrate the issue. Along the way you'll probably discover what's going on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.