How to use Read method of crypto Package

Best K6 code snippet using crypto.Read

encryption-v1_test.go

Source:encryption-v1_test.go Github

copy

Full Screen

...50func TestEncryptRequest(t *testing.T) {51 defer func(flag bool) { globalIsSSL = flag }(globalIsSSL)52 globalIsSSL = true53 for i, test := range encryptRequestTests {54 content := bytes.NewReader(make([]byte, 64))55 req := &http.Request{Header: http.Header{}}56 for k, v := range test.header {57 req.Header.Set(k, v)58 }59 _, _, err := EncryptRequest(content, req, "bucket", "object", test.metadata)60 if err != nil {61 t.Fatalf("Test %d: Failed to encrypt request: %v", i, err)62 }63 if kdf, ok := test.metadata[crypto.SSESealAlgorithm]; !ok {64 t.Errorf("Test %d: ServerSideEncryptionKDF must be part of metadata: %v", i, kdf)65 }66 if iv, ok := test.metadata[crypto.SSEIV]; !ok {67 t.Errorf("Test %d: crypto.SSEIV must be part of metadata: %v", i, iv)68 }69 if mac, ok := test.metadata[crypto.SSECSealedKey]; !ok {70 t.Errorf("Test %d: ServerSideEncryptionKeyMAC must be part of metadata: %v", i, mac)71 }72 }73}74var decryptRequestTests = []struct {75 bucket, object string76 header map[string]string77 metadata map[string]string78 shouldFail bool79}{80 {81 bucket: "bucket",82 object: "object",83 header: map[string]string{84 crypto.SSECAlgorithm: "AES256",85 crypto.SSECKey: "MzJieXRlc2xvbmdzZWNyZXRrZXltdXN0cHJvdmlkZWQ=",86 crypto.SSECKeyMD5: "7PpPLAK26ONlVUGOWlusfg==",87 },88 metadata: map[string]string{89 crypto.SSESealAlgorithm: crypto.InsecureSealAlgorithm,90 crypto.SSEIV: "7nQqotA8xgrPx6QK7Ap3GCfjKitqJSrGP7xzgErSJlw=",91 crypto.SSECSealedKey: "EAAfAAAAAAD7v1hQq3PFRUHsItalxmrJqrOq6FwnbXNarxOOpb8jTWONPPKyM3Gfjkjyj6NCf+aB/VpHCLCTBA==",92 },93 shouldFail: false,94 },95 {96 bucket: "bucket",97 object: "object",98 header: map[string]string{99 crypto.SSECAlgorithm: "AES256",100 crypto.SSECKey: "MzJieXRlc2xvbmdzZWNyZXRrZXltdXN0cHJvdmlkZWQ=",101 crypto.SSECKeyMD5: "7PpPLAK26ONlVUGOWlusfg==",102 },103 metadata: map[string]string{104 crypto.SSESealAlgorithm: crypto.SealAlgorithm,105 crypto.SSEIV: "qEqmsONcorqlcZXJxaw32H04eyXyXwUgjHzlhkaIYrU=",106 crypto.SSECSealedKey: "IAAfAIM14ugTGcM/dIrn4iQMrkl1sjKyeBQ8FBEvRebYj8vWvxG+0cJRpC6NXRU1wJN50JaUOATjO7kz0wZ2mA==",107 },108 shouldFail: false,109 },110 {111 bucket: "bucket",112 object: "object",113 header: map[string]string{114 crypto.SSECAlgorithm: "AES256",115 crypto.SSECKey: "XAm0dRrJsEsyPb1UuFNezv1bl9hxuYsgUVC/MUctE2k=",116 crypto.SSECKeyMD5: "bY4wkxQejw9mUJfo72k53A==",117 },118 metadata: map[string]string{119 crypto.SSESealAlgorithm: "HMAC-SHA3",120 crypto.SSEIV: "XAm0dRrJsEsyPb1UuFNezv1bl9hxuYsgUVC/MUctE2k=",121 crypto.SSECSealedKey: "SY5E9AvI2tI7/nUrUAssIGE32Hcs4rR9z/CUuPqu5N4=",122 },123 shouldFail: true,124 },125 {126 bucket: "bucket",127 object: "object",128 header: map[string]string{129 crypto.SSECAlgorithm: "AES256",130 crypto.SSECKey: "XAm0dRrJsEsyPb1UuFNezv1bl9hxuYsgUVC/MUctE2k=",131 crypto.SSECKeyMD5: "bY4wkxQejw9mUJfo72k53A==",132 },133 metadata: map[string]string{134 crypto.SSESealAlgorithm: crypto.InsecureSealAlgorithm,135 crypto.SSEIV: "RrJsEsyPb1UuFNezv1bl9hxuYsgUVC/MUctE2k=",136 crypto.SSECSealedKey: "SY5E9AvI2tI7/nUrUAssIGE32Hcs4rR9z/CUuPqu5N4=",137 },138 shouldFail: true,139 },140 {141 bucket: "bucket",142 object: "object",143 header: map[string]string{144 crypto.SSECAlgorithm: "AES256",145 crypto.SSECKey: "XAm0dRrJsEsyPb1UuFNezv1bl9hxuYsgUVC/MUctE2k=",146 crypto.SSECKeyMD5: "bY4wkxQejw9mUJfo72k53A==",147 },148 metadata: map[string]string{149 crypto.SSESealAlgorithm: crypto.InsecureSealAlgorithm,150 crypto.SSEIV: "XAm0dRrJsEsyPb1UuFNezv1bl9ehxuYsgUVC/MUctE2k=",151 crypto.SSECSealedKey: "SY5E9AvI2tI7/nUrUAssIGE32Hds4rR9z/CUuPqu5N4=",152 },153 shouldFail: true,154 },155 {156 bucket: "bucket",157 object: "object-2",158 header: map[string]string{159 crypto.SSECAlgorithm: "AES256",160 crypto.SSECKey: "MzJieXRlc2xvbmdzZWNyZXRrZXltdXN0cHJvdmlkZWQ=",161 crypto.SSECKeyMD5: "7PpPLAK26ONlVUGOWlusfg==",162 },163 metadata: map[string]string{164 crypto.SSESealAlgorithm: crypto.SealAlgorithm,165 crypto.SSEIV: "qEqmsONcorqlcZXJxaw32H04eyXyXwUgjHzlhkaIYrU=",166 crypto.SSECSealedKey: "IAAfAIM14ugTGcM/dIrn4iQMrkl1sjKyeBQ8FBEvRebYj8vWvxG+0cJRpC6NXRU1wJN50JaUOATjO7kz0wZ2mA==",167 },168 shouldFail: true,169 },170}171func TestDecryptRequest(t *testing.T) {172 defer func(flag bool) { globalIsSSL = flag }(globalIsSSL)173 globalIsSSL = true174 for i, test := range decryptRequestTests[1:] {175 client := bytes.NewBuffer(nil)176 req := &http.Request{Header: http.Header{}}177 for k, v := range test.header {178 req.Header.Set(k, v)179 }180 _, err := DecryptRequest(client, req, test.bucket, test.object, test.metadata)181 if err != nil && !test.shouldFail {182 t.Fatalf("Test %d: Failed to encrypt request: %v", i, err)183 }184 if err == nil && test.shouldFail {185 t.Fatalf("Test %d: should fail but passed", i)186 }187 if key, ok := test.metadata[crypto.SSECKey]; ok {188 t.Errorf("Test %d: Client provided key survived in metadata - key: %s", i, key)189 }190 if kdf, ok := test.metadata[crypto.SSESealAlgorithm]; ok && !test.shouldFail {191 t.Errorf("Test %d: ServerSideEncryptionKDF should not be part of metadata: %v", i, kdf)192 }193 if iv, ok := test.metadata[crypto.SSEIV]; ok && !test.shouldFail {194 t.Errorf("Test %d: crypto.SSEIV should not be part of metadata: %v", i, iv)195 }196 if mac, ok := test.metadata[crypto.SSECSealedKey]; ok && !test.shouldFail {197 t.Errorf("Test %d: ServerSideEncryptionKeyMAC should not be part of metadata: %v", i, mac)198 }199 }200}201var decryptObjectInfoTests = []struct {202 info ObjectInfo203 headers http.Header204 expErr error205}{206 {207 info: ObjectInfo{Size: 100},208 headers: http.Header{},209 expErr: nil,210 },211 {212 info: ObjectInfo{Size: 100, UserDefined: map[string]string{crypto.SSESealAlgorithm: crypto.InsecureSealAlgorithm}},213 headers: http.Header{crypto.SSECAlgorithm: []string{crypto.SSEAlgorithmAES256}},214 expErr: nil,215 },216 {217 info: ObjectInfo{Size: 0, UserDefined: map[string]string{crypto.SSESealAlgorithm: crypto.InsecureSealAlgorithm}},218 headers: http.Header{crypto.SSECAlgorithm: []string{crypto.SSEAlgorithmAES256}},219 expErr: nil,220 },221 {222 info: ObjectInfo{Size: 100, UserDefined: map[string]string{crypto.SSECSealedKey: "EAAfAAAAAAD7v1hQq3PFRUHsItalxmrJqrOq6FwnbXNarxOOpb8jTWONPPKyM3Gfjkjyj6NCf+aB/VpHCLCTBA=="}},223 headers: http.Header{},224 expErr: errEncryptedObject,225 },226 {227 info: ObjectInfo{Size: 100, UserDefined: map[string]string{}},228 headers: http.Header{crypto.SSECAlgorithm: []string{crypto.SSEAlgorithmAES256}},229 expErr: errInvalidEncryptionParameters,230 },231 {232 info: ObjectInfo{Size: 31, UserDefined: map[string]string{crypto.SSESealAlgorithm: crypto.InsecureSealAlgorithm}},233 headers: http.Header{crypto.SSECAlgorithm: []string{crypto.SSEAlgorithmAES256}},234 expErr: errObjectTampered,235 },236}237func TestDecryptObjectInfo(t *testing.T) {238 for i, test := range decryptObjectInfoTests {239 if encrypted, err := DecryptObjectInfo(&test.info, test.headers); err != test.expErr {240 t.Errorf("Test %d: Decryption returned wrong error code: got %d , want %d", i, err, test.expErr)241 } else if enc := crypto.IsEncrypted(test.info.UserDefined); encrypted && enc != encrypted {242 t.Errorf("Test %d: Decryption thinks object is encrypted but it is not", i)243 } else if !encrypted && enc != encrypted {244 t.Errorf("Test %d: Decryption thinks object is not encrypted but it is", i)245 }246 }247}248// Tests for issue reproduced when getting the right encrypted249// offset of the object.250func TestGetDecryptedRange_Issue50(t *testing.T) {251 rs, err := parseRequestRangeSpec("bytes=594870256-594870263")252 if err != nil {253 t.Fatal(err)254 }255 objInfo := ObjectInfo{256 Bucket: "bucket",257 Name: "object",258 Size: 595160760,259 UserDefined: map[string]string{260 crypto.SSEMultipart: "",261 crypto.SSEIV: "HTexa=",262 crypto.SSESealAlgorithm: "DAREv2-HMAC-SHA256",263 crypto.SSECSealedKey: "IAA8PGAA==",264 ReservedMetadataPrefix + "actual-size": "594870264",265 "content-type": "application/octet-stream",266 "etag": "166b1545b4c1535294ee0686678bea8c-2",267 },268 Parts: []ObjectPartInfo{269 {270 Number: 1,271 Size: 297580380,272 ActualSize: 297435132,273 },274 {275 Number: 2,276 Size: 297580380,277 ActualSize: 297435132,278 },279 },280 }281 encOff, encLength, skipLen, seqNumber, partStart, err := objInfo.GetDecryptedRange(rs)282 if err != nil {283 t.Fatalf("Test: failed %s", err)284 }285 if encOff != 595127964 {286 t.Fatalf("Test: expected %d, got %d", 595127964, encOff)287 }288 if encLength != 32796 {289 t.Fatalf("Test: expected %d, got %d", 32796, encLength)290 }291 if skipLen != 32756 {292 t.Fatalf("Test: expected %d, got %d", 32756, skipLen)293 }294 if seqNumber != 4538 {295 t.Fatalf("Test: expected %d, got %d", 4538, seqNumber)296 }297 if partStart != 1 {298 t.Fatalf("Test: expected %d, got %d", 1, partStart)299 }300}301func TestGetDecryptedRange(t *testing.T) {302 var (303 pkgSz = int64(64) * humanize.KiByte304 minPartSz = int64(5) * humanize.MiByte305 maxPartSz = int64(5) * humanize.GiByte306 getEncSize = func(s int64) int64 {307 v, _ := sio.EncryptedSize(uint64(s))308 return int64(v)309 }310 udMap = func(isMulti bool) map[string]string {311 m := map[string]string{312 crypto.SSESealAlgorithm: crypto.InsecureSealAlgorithm,313 crypto.SSEMultipart: "1",314 }315 if !isMulti {316 delete(m, crypto.SSEMultipart)317 }318 return m319 }320 )321 // Single part object tests322 var (323 mkSPObj = func(s int64) ObjectInfo {324 return ObjectInfo{325 Size: getEncSize(s),326 UserDefined: udMap(false),327 }328 }329 )330 testSP := []struct {331 decSz int64332 oi ObjectInfo333 }{334 {0, mkSPObj(0)},335 {1, mkSPObj(1)},336 {pkgSz - 1, mkSPObj(pkgSz - 1)},337 {pkgSz, mkSPObj(pkgSz)},338 {2*pkgSz - 1, mkSPObj(2*pkgSz - 1)},339 {minPartSz, mkSPObj(minPartSz)},340 {maxPartSz, mkSPObj(maxPartSz)},341 }342 for i, test := range testSP {343 {344 // nil range345 o, l, skip, sn, ps, err := test.oi.GetDecryptedRange(nil)346 if err != nil {347 t.Errorf("Case %d: unexpected err: %v", i, err)348 }349 if skip != 0 || sn != 0 || ps != 0 || o != 0 || l != getEncSize(test.decSz) {350 t.Errorf("Case %d: test failed: %d %d %d %d %d", i, o, l, skip, sn, ps)351 }352 }353 if test.decSz >= 10 {354 // first 10 bytes355 o, l, skip, sn, ps, err := test.oi.GetDecryptedRange(&HTTPRangeSpec{false, 0, 9})356 if err != nil {357 t.Errorf("Case %d: unexpected err: %v", i, err)358 }359 var rLen = pkgSz + 32360 if test.decSz < pkgSz {361 rLen = test.decSz + 32362 }363 if skip != 0 || sn != 0 || ps != 0 || o != 0 || l != rLen {364 t.Errorf("Case %d: test failed: %d %d %d %d %d", i, o, l, skip, sn, ps)365 }366 }367 kb32 := int64(32) * humanize.KiByte368 if test.decSz >= (64+32)*humanize.KiByte {369 // Skip the first 32Kib, and read the next 64Kib370 o, l, skip, sn, ps, err := test.oi.GetDecryptedRange(&HTTPRangeSpec{false, kb32, 3*kb32 - 1})371 if err != nil {372 t.Errorf("Case %d: unexpected err: %v", i, err)373 }374 var rLen = (pkgSz + 32) * 2375 if test.decSz < 2*pkgSz {376 rLen = (pkgSz + 32) + (test.decSz - pkgSz + 32)377 }378 if skip != kb32 || sn != 0 || ps != 0 || o != 0 || l != rLen {379 t.Errorf("Case %d: test failed: %d %d %d %d %d", i, o, l, skip, sn, ps)380 }381 }382 if test.decSz >= (64*2+32)*humanize.KiByte {383 // Skip the first 96Kib and read the next 64Kib384 o, l, skip, sn, ps, err := test.oi.GetDecryptedRange(&HTTPRangeSpec{false, 3 * kb32, 5*kb32 - 1})385 if err != nil {386 t.Errorf("Case %d: unexpected err: %v", i, err)387 }388 var rLen = (pkgSz + 32) * 2389 if test.decSz-pkgSz < 2*pkgSz {390 rLen = (pkgSz + 32) + (test.decSz - pkgSz + 32*2)391 }392 if skip != kb32 || sn != 1 || ps != 0 || o != pkgSz+32 || l != rLen {393 t.Errorf("Case %d: test failed: %d %d %d %d %d", i, o, l, skip, sn, ps)394 }395 }396 }397 // Multipart object tests398 var (399 // make a multipart object-info given part sizes400 mkMPObj = func(sizes []int64) ObjectInfo {401 r := make([]ObjectPartInfo, len(sizes))402 sum := int64(0)403 for i, s := range sizes {404 r[i].Number = i405 r[i].Size = int64(getEncSize(s))406 sum += r[i].Size407 }408 return ObjectInfo{409 Size: sum,410 UserDefined: udMap(true),411 Parts: r,412 }413 }414 // Simple useful utilities415 repeat = func(k int64, n int) []int64 {416 a := []int64{}417 for i := 0; i < n; i++ {418 a = append(a, k)419 }420 return a421 }422 lsum = func(s []int64) int64 {423 sum := int64(0)424 for _, i := range s {425 if i < 0 {426 return -1427 }428 sum += i429 }430 return sum431 }432 esum = func(oi ObjectInfo) int64 {433 sum := int64(0)434 for _, i := range oi.Parts {435 sum += i.Size436 }437 return sum438 }439 )440 s1 := []int64{5487701, 5487799, 3}441 s2 := repeat(5487701, 5)442 s3 := repeat(maxPartSz, 10000)443 testMPs := []struct {444 decSizes []int64445 oi ObjectInfo446 }{447 {s1, mkMPObj(s1)},448 {s2, mkMPObj(s2)},449 {s3, mkMPObj(s3)},450 }451 // This function is a reference (re-)implementation of452 // decrypted range computation, written solely for the purpose453 // of the unit tests.454 //455 // `s` gives the decrypted part sizes, and the other456 // parameters describe the desired read segment. When457 // `isFromEnd` is true, `skipLen` argument is ignored.458 decryptedRangeRef := func(s []int64, skipLen, readLen int64, isFromEnd bool) (o, l, skip int64, sn uint32, ps int) {459 oSize := lsum(s)460 if isFromEnd {461 skipLen = oSize - readLen462 }463 if skipLen < 0 || readLen < 0 || oSize < 0 || skipLen+readLen > oSize {464 t.Fatalf("Impossible read specified: %d %d %d", skipLen, readLen, oSize)465 }466 var cumulativeSum, cumulativeEncSum int64467 toRead := readLen468 readStart := false469 for i, v := range s {470 partOffset := int64(0)471 partDarePkgOffset := int64(0)472 if !readStart && cumulativeSum+v > skipLen {473 // Read starts at the current part474 readStart = true475 partOffset = skipLen - cumulativeSum476 // All return values except `l` are477 // calculated here.478 sn = uint32(partOffset / pkgSz)479 skip = partOffset % pkgSz480 ps = i481 o = cumulativeEncSum + int64(sn)*(pkgSz+32)482 partDarePkgOffset = partOffset - skip483 }484 if readStart {485 currentPartBytes := v - partOffset486 currentPartDareBytes := v - partDarePkgOffset487 if currentPartBytes < toRead {488 toRead -= currentPartBytes489 l += getEncSize(currentPartDareBytes)490 } else {491 // current part has the last492 // byte required493 lbPartOffset := partOffset + toRead - 1494 // round up the lbPartOffset495 // to the end of the496 // corresponding DARE package497 lbPkgEndOffset := lbPartOffset - (lbPartOffset % pkgSz) + pkgSz498 if lbPkgEndOffset > v {499 lbPkgEndOffset = v500 }501 bytesToDrop := v - lbPkgEndOffset502 // Last segment to update `l`503 l += getEncSize(currentPartDareBytes - bytesToDrop)504 break505 }506 }507 cumulativeSum += v508 cumulativeEncSum += getEncSize(v)509 }510 return511 }512 for i, test := range testMPs {513 {514 // nil range515 o, l, skip, sn, ps, err := test.oi.GetDecryptedRange(nil)516 if err != nil {517 t.Errorf("Case %d: unexpected err: %v", i, err)518 }519 if o != 0 || l != esum(test.oi) || skip != 0 || sn != 0 || ps != 0 {520 t.Errorf("Case %d: test failed: %d %d %d %d %d", i, o, l, skip, sn, ps)521 }522 }523 // Skip 1Mib and read 1Mib (in the decrypted object)524 //525 // The check below ensures the object is large enough526 // for the read.527 if lsum(test.decSizes) >= 2*humanize.MiByte {528 skipLen, readLen := int64(1)*humanize.MiByte, int64(1)*humanize.MiByte529 o, l, skip, sn, ps, err := test.oi.GetDecryptedRange(&HTTPRangeSpec{false, skipLen, skipLen + readLen - 1})530 if err != nil {531 t.Errorf("Case %d: unexpected err: %v", i, err)532 }533 oRef, lRef, skipRef, snRef, psRef := decryptedRangeRef(test.decSizes, skipLen, readLen, false)534 if o != oRef || l != lRef || skip != skipRef || sn != snRef || ps != psRef {535 t.Errorf("Case %d: test failed: %d %d %d %d %d (Ref: %d %d %d %d %d)",536 i, o, l, skip, sn, ps, oRef, lRef, skipRef, snRef, psRef)537 }538 }539 // Read the last 6Mib+1 bytes of the (decrypted)540 // object541 //542 // The check below ensures the object is large enough543 // for the read.544 readLen := int64(6)*humanize.MiByte + 1545 if lsum(test.decSizes) >= readLen {546 o, l, skip, sn, ps, err := test.oi.GetDecryptedRange(&HTTPRangeSpec{true, -readLen, -1})547 if err != nil {548 t.Errorf("Case %d: unexpected err: %v", i, err)549 }550 oRef, lRef, skipRef, snRef, psRef := decryptedRangeRef(test.decSizes, 0, readLen, true)551 if o != oRef || l != lRef || skip != skipRef || sn != snRef || ps != psRef {552 t.Errorf("Case %d: test failed: %d %d %d %d %d (Ref: %d %d %d %d %d)",553 i, o, l, skip, sn, ps, oRef, lRef, skipRef, snRef, psRef)...

Full Screen

Full Screen

crypto.go

Source:crypto.go Github

copy

Full Screen

...63 vc = make([]byte, 8)64}65func randomInt() (*big.Int, error) {66 buf := make([]byte, 20)67 _, err := crand.Read(buf)68 if err != nil {69 return nil, err70 }71 var x big.Int72 x.SetBytes(buf)73 return &x, nil74}75func hash(v ...[]byte) []byte {76 h := sha1.New()77 for _, w := range v {78 h.Write(w)79 }80 return h.Sum(nil)81}82func len2(v []byte) []byte {83 w := make([]byte, 2)84 w[0] = byte(len(v) >> 8)85 w[1] = byte(len(v) & 0xFF)86 return w87}88func xor(v1 []byte, v2 []byte) []byte {89 if len(v1) != len(v2) {90 panic("xor: wrong length")91 }92 v := make([]byte, len(v1))93 for i := range v1 {94 v[i] = v1[i] ^ v2[i]95 }96 return v97}98func synchronise(c io.Reader, w []byte, v []byte, n, m int) ([]byte, error) {99 if m < n {100 m = n101 }102 for {103 i := bytes.Index(w, v)104 if i >= 0 {105 return w[i+len(v):], nil106 }107 l := len(w)108 if l >= n {109 return w, errors.New("couldn't synchronise")110 }111 w = append(w, make([]byte, m-l)...)112 k, err := c.Read(w[l:])113 w = w[:l+k]114 if k == 0 && err != nil {115 return w, err116 }117 }118}119func writeAsync(conn net.Conn, v []byte) <-chan error {120 ch := make(chan error, 1)121 go func() {122 _, err := conn.Write(v)123 ch <- err124 }()125 return ch126}127func writeWithPad(conn net.Conn, v *big.Int) <-chan error {128 lbuf := make([]byte, 2)129 crand.Read(lbuf)130 lbuf[0] &= 1131 length := uint16(lbuf[0])<<8 | uint16(lbuf[1])132 buf := make([]byte, 768/8+int(length))133 v.FillBytes(buf[:768/8])134 crand.Read(buf[768/8:])135 return writeAsync(conn, buf)136}137func readMore(conn net.Conn, buf []byte, n int, m int) ([]byte, error) {138 if m < n {139 m = n140 }141 l := len(buf)142 if l >= n {143 return buf, nil144 }145 buf = append(buf, make([]byte, m-l)...)146 _, err := io.ReadAtLeast(conn, buf[l:], n-l)147 return buf, err148}149func trivial(x *big.Int) bool {150 return x.Cmp(&zero) == 0 || x.Cmp(&one) == 0 || x.Cmp(&p1) == 0151}152// ClientHandshake performs the client side of the BitTorrent protocol153// encryption handshake. It returns an encrypted connection and any154// cleartext that was received together with the handshake.155func ClientHandshake(c net.Conn, skey []byte, ia []byte, options *Options) (conn net.Conn, buf []byte, err error) {156 conn = c157 if !options.AllowCryptoHandshake {158 err = errors.New("crypto handshake forbidden")159 return160 }161 xa, err := randomInt()162 if err != nil {163 return164 }165 var ya, yb, s big.Int166 ya.Exp(&g, xa, &p)167 ch := writeWithPad(conn, &ya)168 buf = make([]byte, 608)169 n, err := io.ReadAtLeast(conn, buf, 768/8)170 if err != nil {171 return172 }173 yb.SetBytes(buf[:768/8])174 if trivial(&yb) {175 err = errors.New("peer returned trivial public key")176 return177 }178 s.Exp(&yb, xa, &p)179 buf = buf[768/8 : n]180 err = <-ch181 if err != nil {182 return183 }184 sb := make([]byte, 768/8)185 s.FillBytes(sb)186 enc, err := rc4.NewCipher(hash([]byte("keyA"), sb, skey))187 if err != nil {188 return189 }190 discard := make([]byte, 1024)191 enc.XORKeyStream(discard, discard)192 encrypt := func(v ...[]byte) []byte {193 n := 0194 for _, vv := range v {195 n += len(vv)196 }197 w := make([]byte, n)198 i := 0199 for _, vv := range v {200 enc.XORKeyStream(w[i:], vv)201 i += len(vv)202 }203 return w204 }205 dec, err := rc4.NewCipher(hash([]byte("keyB"), sb, skey))206 if err != nil {207 return208 }209 dec.XORKeyStream(discard, discard)210 decrypt := func(v []byte) []byte {211 w := make([]byte, len(v))212 dec.XORKeyStream(w, v)213 return w214 }215 wbuf := append(216 hash([]byte("req1"), sb),217 xor(hash([]byte("req2"), skey), hash([]byte("req3"), sb))...)218 cryptoProvide := make([]byte, 4)219 if !options.ForceEncryption {220 cryptoProvide[3] |= 1221 }222 if options.AllowEncryption {223 cryptoProvide[3] |= 2224 }225 if cryptoProvide[3] == 0 {226 err = errors.New("couldn't negotiate encryption")227 return228 }229 wbuf = append(wbuf,230 encrypt(vc, cryptoProvide, []byte{0, 0}, len2(ia), ia)...)231 ch = writeAsync(conn, wbuf)232 buf, err = synchronise(conn, buf, decrypt(vc),233 len(vc)+512, len(vc)+512+4+2)234 if err != nil {235 return236 }237 err = <-ch238 if err != nil {239 return240 }241 buf, err = readMore(conn, buf, 4+2, 0)242 if err != nil {243 return244 }245 stuff := decrypt(buf[:4+2])246 buf = buf[4+2:]247 cryptoSelect :=248 uint32(stuff[0])<<24 |249 uint32(stuff[1])<<16 |250 uint32(stuff[2])<<8 |251 uint32(stuff[3])252 lenPadD := uint16(stuff[4])<<8 | uint16(stuff[5])253 if lenPadD > 0 {254 buf, err = readMore(conn, buf, int(lenPadD), 0)255 if err != nil {256 return257 }258 decrypt(buf[:lenPadD])259 buf = buf[lenPadD:]260 }261 switch cryptoSelect {262 case 1:263 if options.ForceEncryption {264 err = errors.New("peer didn't negotiate encryption")265 }266 buf2 := make([]byte, len(buf))267 copy(buf2, buf)268 buf = buf2269 return270 case 2:271 if !options.AllowEncryption {272 err = errors.New("peer did negotiate encryption")273 return274 }275 buf = decrypt(buf)276 conn = &Conn{conn: conn, enc: enc, dec: dec}277 return278 default:279 err = errors.New("bad value for cryptoSelect")280 return281 }282}283// ServerHandshake performs the server side of the BitTorrent protocol284// encryption handshake. It returns an encrypted connection, the skey285// that was agreed upon (a torrent hash), and any cleartext that was286// included within the handshake.287func ServerHandshake(c net.Conn, head []byte, skeys [][]byte, options *Options) (conn net.Conn, skey []byte, ia []byte, err error) {288 conn = c289 if !options.AllowCryptoHandshake {290 err = errors.New("crypto handshake forbidden")291 return292 }293 if len(head) > 768/8 {294 err = errors.New("unexpected length for encrypted header")295 return296 }297 var ya, yb, s big.Int298 buf := make([]byte, 608)299 copy(buf, head)300 n := len(head)301 if n < 768/8 {302 var m int303 m, err = io.ReadAtLeast(conn, buf[n:], 768/8-n)304 if err != nil {305 return306 }307 n += m308 }309 ya.SetBytes(buf[:768/8])310 if trivial(&ya) {311 err = errors.New("peer sent trivial public key")312 return313 }314 buf = buf[768/8 : n]315 xb, err := randomInt()316 if err != nil {317 return nil, nil, nil, err...

Full Screen

Full Screen

reader.go

Source:reader.go Github

copy

Full Screen

2import (3 "io"4 "github.com/foxxorcat/DriverCore/tools"5)6type cryptoReader struct {7 crypto func(dst []byte, src []byte)8 reader io.Reader9 offset int10 isInit bool11 data []byte // 加密后数据12 buf []byte13}14// Stream15type cryptoStream struct {16 cryptoReader17 bufSize int // 块大小18}19func (a *cryptoStream) Read(p []byte) (n int, err error) {20 if a.offset >= len(a.data) {21 if !a.isInit {22 a.data, a.buf, a.isInit = make([]byte, a.bufSize), make([]byte, a.bufSize), true23 }24 n, err = a.reader.Read(a.buf)25 a.crypto(a.data[:n], a.buf[:n])26 a.offset, a.data = 0, a.data[:n]27 }28 n = copy(p, a.data[a.offset:])29 a.offset += n30 return31}32// Block33type cryptoBlockEncrypt struct {34 cryptoReader35 blockSize int36 readFull bool37}38func (a *cryptoBlockEncrypt) Read(p []byte) (n int, err error) {39 if a.offset >= len(a.data) {40 if !a.isInit {41 a.data, a.buf, a.isInit = make([]byte, a.blockSize), make([]byte, a.blockSize), true42 }43 if a.readFull {44 return 0, io.EOF45 }46 n, err = io.ReadAtLeast(a.reader, a.buf, a.blockSize)47 if (err == io.EOF || err == io.ErrUnexpectedEOF) && !a.readFull {48 a.buf, a.readFull, n = tools.PKCS7Padding(a.buf[:n], a.blockSize), true, a.blockSize49 }50 a.crypto(a.data[:n], a.buf[:n])51 a.offset, a.data = 0, a.data[:n]52 }53 n = copy(p, a.data[a.offset:])54 a.offset += n55 return56}57type cryptoBlockDecrypt struct {58 cryptoReader59 blockSize int60}61func (a *cryptoBlockDecrypt) Read(p []byte) (n int, err error) {62 if a.offset >= len(a.data) {63 if !a.isInit {64 a.data, a.buf, a.isInit = make([]byte, a.blockSize), make([]byte, a.blockSize), true65 if n, err = io.ReadAtLeast(a.reader, a.buf[:1], 1); err != nil {66 return67 }68 }69 if _, err = io.ReadAtLeast(a.reader, a.buf[1:], a.blockSize-1); err != nil {70 return 0, err71 }72 a.crypto(a.data, a.buf)73 a.offset = 074 // 再次读取判断是否到尾部75 if n, err = io.ReadAtLeast(a.reader, a.buf[:1], 1); err != nil {76 if err != io.EOF {77 return78 }79 a.data = tools.PKCS7UnPadding(a.data)80 }81 }82 n = copy(p, a.data[a.offset:])83 a.offset += n84 return85}...

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 b := make([]byte, 16)4 _, err := rand.Read(b)5 if err != nil {6 fmt.Println("Error:", err)7 }8 fmt.Printf("%x9}10import (11func main() {12 b := make([]byte, 16)13 _, err := rand.Read(b)14 if err != nil {15 fmt.Println("Error:", err)16 }17 fmt.Printf("%x18}19import (20func main() {21 b := make([]byte, 16)22 _, err := rand.Read(b)23 if err != nil {24 fmt.Println("Error:", err)25 }26 fmt.Printf("%x27}28import (29func main() {30 b := make([]byte, 16)31 _, err := rand.Read(b)32 if err != nil {33 fmt.Println("Error:", err)34 }35 fmt.Printf("%x36}37import (

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 b := make([]byte, 16)4 _, err := rand.Read(b)5 if err != nil {6 fmt.Println("error:", err)7 }8 fmt.Printf("%x9}10import (11func main() {12 b := make([]byte, 16)13 _, err := rand.ReadAt(b, 0)14 if err != nil {15 fmt.Println("error:", err)16 }17 fmt.Printf("%x18}19import (20func main() {21 b := make([]byte, 16)22 _, err := rand.Read(b)23 if err != nil {24 fmt.Println("error:", err)25 }26 fmt.Printf("%x27}28import (29func main() {30 b := make([]byte, 16)31 _, err := rand.ReadAt(b, 0)32 if err != nil {33 fmt.Println("error:", err)34 }35 fmt.Printf("%x36}37import (

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 b := make([]byte, 32)4 n, err := rand.Read(b)5 fmt.Println(n, err, b)6}

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f, err := os.Open("C:/Users/username/Documents/Go/1.txt")4 if err != nil {5 fmt.Println(err)6 }7 defer f.Close()8 h := sha256.New()9 if _, err := io.Copy(h, f); err != nil {10 fmt.Println(err)

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1 fmt.Println("")2}3import (4func main() {5 fmt.Println("MD5 Hashing")6 fmt.Println("

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1 fmt.Println("")2}3import (4func main() {5 fmt.Println("MD5 Hashing")6 fmt.Println("

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1 fmt.Println("")2}3import (4func main() {5 fmt.Println("MD5 Hashing")6 fmt.Println("

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 b := make([]byte, 5)4 _, err := rand.Read(b)5 if err != nil {6 fmt.Println("error:", err)7 }8 fmt.Printf("%x9}10import (11func main() {12 b := make([]byte, 5)13 _, err := rand.Read(b)14 if err != nil {15 fmt.Println("error:", err)16 }17 fmt.Printf("%x18}19import (20func main() {21 b := make([]byte, 5)22 _, err := rand.Read(b)23 if err != nil {24 fmt.Println("error:", err)25 }26 fmt.Printf("%x27}28import (29func main() {30 b := make([]byte, 5)31 _, err := rand.Read(b)32 if err != nil {33 fmt.Println("error:", err)34 }35 fmt.Printf("%x36}37import (38func main() {39 b := make([]byte, 5)40 _, err := rand.Read(b)41 if err != nil {42 fmt.Println("error:", err)43 }44 fmt.Printf("%x45}46import (47func main() {48 b := make([]byte,

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 key, err := ioutil.ReadFile("key.txt")4 if err != nil {5 fmt.Println("Error in reading the key")6 os.Exit(1)7 }8 data, err := ioutil.ReadFile("data.txt")9 if err != nil {10 fmt.Println("Error in reading the data")11 os.Exit(1)12 }13 decoded, err := hex.DecodeString(string(data))14 if err != nil {15 fmt.Println("Error in decoding the data")16 os.Exit(1)17 }18 block, err := aes.NewCipher(key)19 if err != nil {20 fmt.Println("Error in creating the cipher block")21 os.Exit(1)22 }23 gcm, err := cipher.NewGCM(block)24 if err != nil {25 fmt.Println("Error in creating the GCM")26 os.Exit(1)27 }28 nonceSize := gcm.NonceSize()29 plaintext, err := gcm.Open(nil, nonce, cipherText, nil)30 if err != nil {31 fmt.Println("Error in decrypting the data")32 os.Exit(1)33 }34 err = ioutil.WriteFile("newdata.txt", plaintext, 0777)35 if err != nil {36 fmt.Println("Error in writing the data to the file")37 os.Exit(1)38 }39 fmt.Println("Done")40}

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 buf := make([]byte, 10)4 rand.Read(buf)5 fmt.Println(buf)6}7import (8func main() {9 buf := make([]byte, 10)10 _, err := rand.Read(buf)11 if err != nil {12 fmt.Println("Error:", err)13 }14 fmt.Println(buf)15}16import (17func main() {18 buf := make([]byte, 10)19 _, err := rand.Read(buf)20 if err != nil {21 fmt.Println("Error:", err)22 }23 fmt.Println(buf)24}25import (26func main() {27 buf := make([]byte, 10)28 _, err := rand.Read(buf)29 if err != nil {30 fmt.Println("Error:", err)31 }32 fmt.Println(buf)33}34import (35func main() {36 buf := make([]byte, 10)37 _, err := rand.Read(buf)38 if err != nil {39 fmt.Println("Error:", err)40 }41 fmt.Println(buf)42}43import (44func main() {45 buf := make([]byte, 10)46 _, err := rand.Read(buf)47 if err != nil {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful