4d84a934
曹明
初始代码提交
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
<?php
/**
* Signature create related functions for authenticating with cos system.
*/
namespace qcloudcos;
/**
* Auth class for creating reusable or nonreusable signature.
*/
class Auth {
// Secret id or secret key is not valid.
const AUTH_SECRET_ID_KEY_ERROR = -1;
/**
* Create reusable signature for listDirectory in $bucket or uploadFile into $bucket.
* If $filepath is not null, this signature will be binded with this $filepath.
* This signature will expire at $expiration timestamp.
* Return the signature on success.
* Return error code if parameter is not valid.
*/
public static function createReusableSignature($expiration, $bucket, $filepath = null) {
$appId = Conf::APP_ID;
$secretId = Conf::SECRET_ID;
$secretKey = Conf::SECRET_KEY;
if (empty($appId) || empty($secretId) || empty($secretKey)) {
return self::AUTH_SECRET_ID_KEY_ERROR;
}
if (empty($filepath)) {
return self::createSignature($appId, $secretId, $secretKey, $expiration, $bucket, null);
} else {
if (preg_match('/^\//', $filepath) == 0) {
$filepath = '/' . $filepath;
}
return self::createSignature($appId, $secretId, $secretKey, $expiration, $bucket, $filepath);
}
}
/**
* Create nonreusable signature for delete $filepath in $bucket.
* This signature will expire after single usage.
* Return the signature on success.
* Return error code if parameter is not valid.
*/
public static function createNonreusableSignature($bucket, $filepath) {
$appId = Conf::APP_ID;
$secretId = Conf::SECRET_ID;
$secretKey = Conf::SECRET_KEY;
if (empty($appId) || empty($secretId) || empty($secretKey)) {
return self::AUTH_SECRET_ID_KEY_ERROR;
}
if (preg_match('/^\//', $filepath) == 0) {
$filepath = '/' . $filepath;
}
$fileId = '/' . $appId . '/' . $bucket . $filepath;
return self::createSignature($appId, $secretId, $secretKey, 0, $bucket, $fileId);
}
/**
* A helper function for creating signature.
* Return the signature on success.
* Return error code if parameter is not valid.
*/
private static function createSignature(
$appId, $secretId, $secretKey, $expiration, $bucket, $fileId) {
if (empty($secretId) || empty($secretKey)) {
return self::AUTH_SECRET_ID_KEY_ERROR;
}
$now = time();
$random = rand();
$plainText = "a=$appId&k=$secretId&e=$expiration&t=$now&r=$random&f=$fileId&b=$bucket";
$bin = hash_hmac('SHA1', $plainText, $secretKey, true);
$bin = $bin.$plainText;
$signature = base64_encode($bin);
return $signature;
}
}
|