Ninja
Ninja

Reputation: 105

Covert REST-generated key to gcloud format

I'm trying to convert the key generated by calling a REST API in spring boot which is returned in this format:

{
  "name": "projects/project-id/serviceAccounts/service-account-email/keys/key-id",
  "privateKeyType": "TYPE_GOOGLE_CREDENTIALS_FILE",
  "privateKeyData": "private-key",
  "validAfterTime": "date",
  "validBeforeTime": "date",
  "keyAlgorithm": "KEY_ALG_RSA_2048"
}

While the required format is this:

{
  "type": "service_account",
  "project_id": "project-id",
  "private_key_id": "key-id",
  "private_key": "-----BEGIN PRIVATE KEY-----\nprivate-key\n-----END PRIVATE KEY-----\n",
  "client_email": "service-account-email",
  "client_id": "client-id",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service-account-email"
}

The issue is I've edited the returned key to match the second format but keep getting this error:

> java.io.IOException: Error reading credential file from environment
> variable GOOGLE_APPLICATION_CREDENTIALS, value
> 'C:\Users\user\Desktop\*****\********\src\main\resources\key.json':
> Unexpected exception reading PKCS#8 data
>         at 

com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentialsUnsynchronized(DefaultCredentialsProvider.java:162)

  ... 99 more
Caused by: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
        at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:252)
        at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
        at com.google.auth.oauth2.ServiceAccountCredentials.privateKeyFromPkcs8(ServiceAccountCredentials.java:342)
        ... 103 more
Caused by: java.security.InvalidKeyException: invalid key format

Upvotes: 0

Views: 501

Answers (1)

Ninja
Ninja

Reputation: 105

Solved by decoding the PrivateKeyData base64 using

import org.apache.commons.codec.binary.Base64;

String string = key.getPrivateKeyData(); 
byte[] byteArray = Base64.decodeBase64(string.getBytes()); 
String decodedString = new String(byteArray); 
System.out.println(decodedString);

Upvotes: 1

Related Questions