我正在使用GAE中生成的服務帳戶密鑰,在客戶端使用serviceAccounts.keys.create
Google IAM API將文件上傳到GCS。此API返回privateKeyData
場。我正在使用的客戶端代碼如下:如何在Java的客戶端使用使用serviceAccounts.keys.create API生成的Google雲平臺服務帳戶密鑰?
public class GCSTest {
public static final String CLOUD_STORAGE_SCOPE =
"https://www.googleapis.com/auth/cloud-platform";
private GoogleCredential credential = null;
private HttpTransport HTTP_TRANSPORT = null;
private Storage storage = null;
private final JsonFactory json_factory = JacksonFactory
.getDefaultInstance();
public String APPLICATION_NAME = "GCSTest";
private String privKeyString =
<copy the privateKeyData from response of serviceAccounts.keys.create>;
public void startTests() {
initStorageService();
writeObject();
}
private void initStorageService() {
List<String> scopeList = new ArrayList<String>();
scopeList.add(CLOUD_STORAGE_SCOPE);
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
byte[] privKeyBytes = Base64.decodeBase64(privKeyString.getBytes());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privKeyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privateKey = kf.generatePrivate(spec);
credential =
new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(json_factory)
.setServiceAccountId(
"<service_account_name>@<project-id>.iam.gserviceaccount.com")
.setServiceAccountScopes(scopeList)
.setServiceAccountPrivateKey(privateKey)
.setServiceAccountPrivateKeyId(
"<key_id>")
.build();
storage =
new Storage.Builder(HTTP_TRANSPORT, json_factory,
credential).setApplicationName(APPLICATION_NAME)
.build();
}
private void writeObject() {
String fileName = "StorageSample";
Path tempPath = Files.createTempFile(fileName, ".txt");;
Files.write(tempPath, "Sample file".getBytes());
File tempFile = tempPath.toFile();
tempFile.deleteOnExit();
InputStreamContent contentStream =
new InputStreamContent("text/plain", new FileInputStream(
tempFile));
contentStream.setLength(tempFile.length());
StorageObject objectMetadata = new StorageObject().setName(fileName);
Storage.Objects.Insert insert =
storage.objects().insert(<bucket_name>,
objectMetadata, contentStream);;
insert.setName(fileName);
insert.execute();
}
}
不過,我得到java.security.InvalidKeyException: invalid key format exception
時storage.objects().insert
被調用。 這是使用服務帳戶密鑰生成GoogleCredential
的正確方法嗎? P.S:我知道JSON或P12密鑰文件。我不想使用它,因爲它不適合我的用例。
謝謝。我使用'TYPE_PKCS12_FILE'生成密鑰,但現在我得到了'java.security.InvalidKeyException:IOException:版本不匹配:(支持:00,解析:03'錯誤。 –